asn1.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. // Copyright 2009 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 asn1 implements parsing of DER-encoded ASN.1 data structures,
  5. // as defined in ITU-T Rec X.690.
  6. //
  7. // See also ``A Layman's Guide to a Subset of ASN.1, BER, and DER,''
  8. // http://luca.ntop.org/Teaching/Appunti/asn1.html.
  9. //
  10. // START CT CHANGES
  11. // This is a fork of the Go standard library ASN.1 implementation
  12. // (encoding/asn1). The main difference is that this version tries to correct
  13. // for errors (e.g. use of tagPrintableString when the string data is really
  14. // ISO8859-1 - a common error present in many x509 certificates in the wild.)
  15. // END CT CHANGES
  16. package asn1
  17. // ASN.1 is a syntax for specifying abstract objects and BER, DER, PER, XER etc
  18. // are different encoding formats for those objects. Here, we'll be dealing
  19. // with DER, the Distinguished Encoding Rules. DER is used in X.509 because
  20. // it's fast to parse and, unlike BER, has a unique encoding for every object.
  21. // When calculating hashes over objects, it's important that the resulting
  22. // bytes be the same at both ends and DER removes this margin of error.
  23. //
  24. // ASN.1 is very complex and this package doesn't attempt to implement
  25. // everything by any means.
  26. import (
  27. // START CT CHANGES
  28. "errors"
  29. "fmt"
  30. // END CT CHANGES
  31. "math/big"
  32. "reflect"
  33. // START CT CHANGES
  34. "strings"
  35. // END CT CHANGES
  36. "time"
  37. )
  38. // A StructuralError suggests that the ASN.1 data is valid, but the Go type
  39. // which is receiving it doesn't match.
  40. type StructuralError struct {
  41. Msg string
  42. }
  43. func (e StructuralError) Error() string { return "asn1: structure error: " + e.Msg }
  44. // A SyntaxError suggests that the ASN.1 data is invalid.
  45. type SyntaxError struct {
  46. Msg string
  47. }
  48. func (e SyntaxError) Error() string { return "asn1: syntax error: " + e.Msg }
  49. // We start by dealing with each of the primitive types in turn.
  50. // BOOLEAN
  51. func parseBool(bytes []byte) (ret bool, err error) {
  52. if len(bytes) != 1 {
  53. err = SyntaxError{"invalid boolean"}
  54. return
  55. }
  56. // DER demands that "If the encoding represents the boolean value TRUE,
  57. // its single contents octet shall have all eight bits set to one."
  58. // Thus only 0 and 255 are valid encoded values.
  59. switch bytes[0] {
  60. case 0:
  61. ret = false
  62. case 0xff:
  63. ret = true
  64. default:
  65. err = SyntaxError{"invalid boolean"}
  66. }
  67. return
  68. }
  69. // INTEGER
  70. // parseInt64 treats the given bytes as a big-endian, signed integer and
  71. // returns the result.
  72. func parseInt64(bytes []byte) (ret int64, err error) {
  73. if len(bytes) > 8 {
  74. // We'll overflow an int64 in this case.
  75. err = StructuralError{"integer too large"}
  76. return
  77. }
  78. for bytesRead := 0; bytesRead < len(bytes); bytesRead++ {
  79. ret <<= 8
  80. ret |= int64(bytes[bytesRead])
  81. }
  82. // Shift up and down in order to sign extend the result.
  83. ret <<= 64 - uint8(len(bytes))*8
  84. ret >>= 64 - uint8(len(bytes))*8
  85. return
  86. }
  87. // parseInt treats the given bytes as a big-endian, signed integer and returns
  88. // the result.
  89. func parseInt32(bytes []byte) (int32, error) {
  90. ret64, err := parseInt64(bytes)
  91. if err != nil {
  92. return 0, err
  93. }
  94. if ret64 != int64(int32(ret64)) {
  95. return 0, StructuralError{"integer too large"}
  96. }
  97. return int32(ret64), nil
  98. }
  99. var bigOne = big.NewInt(1)
  100. // parseBigInt treats the given bytes as a big-endian, signed integer and returns
  101. // the result.
  102. func parseBigInt(bytes []byte) *big.Int {
  103. ret := new(big.Int)
  104. if len(bytes) > 0 && bytes[0]&0x80 == 0x80 {
  105. // This is a negative number.
  106. notBytes := make([]byte, len(bytes))
  107. for i := range notBytes {
  108. notBytes[i] = ^bytes[i]
  109. }
  110. ret.SetBytes(notBytes)
  111. ret.Add(ret, bigOne)
  112. ret.Neg(ret)
  113. return ret
  114. }
  115. ret.SetBytes(bytes)
  116. return ret
  117. }
  118. // BIT STRING
  119. // BitString is the structure to use when you want an ASN.1 BIT STRING type. A
  120. // bit string is padded up to the nearest byte in memory and the number of
  121. // valid bits is recorded. Padding bits will be zero.
  122. type BitString struct {
  123. Bytes []byte // bits packed into bytes.
  124. BitLength int // length in bits.
  125. }
  126. // At returns the bit at the given index. If the index is out of range it
  127. // returns false.
  128. func (b BitString) At(i int) int {
  129. if i < 0 || i >= b.BitLength {
  130. return 0
  131. }
  132. x := i / 8
  133. y := 7 - uint(i%8)
  134. return int(b.Bytes[x]>>y) & 1
  135. }
  136. // RightAlign returns a slice where the padding bits are at the beginning. The
  137. // slice may share memory with the BitString.
  138. func (b BitString) RightAlign() []byte {
  139. shift := uint(8 - (b.BitLength % 8))
  140. if shift == 8 || len(b.Bytes) == 0 {
  141. return b.Bytes
  142. }
  143. a := make([]byte, len(b.Bytes))
  144. a[0] = b.Bytes[0] >> shift
  145. for i := 1; i < len(b.Bytes); i++ {
  146. a[i] = b.Bytes[i-1] << (8 - shift)
  147. a[i] |= b.Bytes[i] >> shift
  148. }
  149. return a
  150. }
  151. // parseBitString parses an ASN.1 bit string from the given byte slice and returns it.
  152. func parseBitString(bytes []byte) (ret BitString, err error) {
  153. if len(bytes) == 0 {
  154. err = SyntaxError{"zero length BIT STRING"}
  155. return
  156. }
  157. paddingBits := int(bytes[0])
  158. if paddingBits > 7 ||
  159. len(bytes) == 1 && paddingBits > 0 ||
  160. bytes[len(bytes)-1]&((1<<bytes[0])-1) != 0 {
  161. err = SyntaxError{"invalid padding bits in BIT STRING"}
  162. return
  163. }
  164. ret.BitLength = (len(bytes)-1)*8 - paddingBits
  165. ret.Bytes = bytes[1:]
  166. return
  167. }
  168. // OBJECT IDENTIFIER
  169. // An ObjectIdentifier represents an ASN.1 OBJECT IDENTIFIER.
  170. type ObjectIdentifier []int
  171. // Equal reports whether oi and other represent the same identifier.
  172. func (oi ObjectIdentifier) Equal(other ObjectIdentifier) bool {
  173. if len(oi) != len(other) {
  174. return false
  175. }
  176. for i := 0; i < len(oi); i++ {
  177. if oi[i] != other[i] {
  178. return false
  179. }
  180. }
  181. return true
  182. }
  183. // parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and
  184. // returns it. An object identifier is a sequence of variable length integers
  185. // that are assigned in a hierarchy.
  186. func parseObjectIdentifier(bytes []byte) (s []int, err error) {
  187. if len(bytes) == 0 {
  188. err = SyntaxError{"zero length OBJECT IDENTIFIER"}
  189. return
  190. }
  191. // In the worst case, we get two elements from the first byte (which is
  192. // encoded differently) and then every varint is a single byte long.
  193. s = make([]int, len(bytes)+1)
  194. // The first varint is 40*value1 + value2:
  195. // According to this packing, value1 can take the values 0, 1 and 2 only.
  196. // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2,
  197. // then there are no restrictions on value2.
  198. v, offset, err := parseBase128Int(bytes, 0)
  199. if err != nil {
  200. return
  201. }
  202. if v < 80 {
  203. s[0] = v / 40
  204. s[1] = v % 40
  205. } else {
  206. s[0] = 2
  207. s[1] = v - 80
  208. }
  209. i := 2
  210. for ; offset < len(bytes); i++ {
  211. v, offset, err = parseBase128Int(bytes, offset)
  212. if err != nil {
  213. return
  214. }
  215. s[i] = v
  216. }
  217. s = s[0:i]
  218. return
  219. }
  220. // ENUMERATED
  221. // An Enumerated is represented as a plain int.
  222. type Enumerated int
  223. // FLAG
  224. // A Flag accepts any data and is set to true if present.
  225. type Flag bool
  226. // parseBase128Int parses a base-128 encoded int from the given offset in the
  227. // given byte slice. It returns the value and the new offset.
  228. func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) {
  229. offset = initOffset
  230. for shifted := 0; offset < len(bytes); shifted++ {
  231. if shifted > 4 {
  232. err = StructuralError{"base 128 integer too large"}
  233. return
  234. }
  235. ret <<= 7
  236. b := bytes[offset]
  237. ret |= int(b & 0x7f)
  238. offset++
  239. if b&0x80 == 0 {
  240. return
  241. }
  242. }
  243. err = SyntaxError{"truncated base 128 integer"}
  244. return
  245. }
  246. // UTCTime
  247. func parseUTCTime(bytes []byte) (ret time.Time, err error) {
  248. s := string(bytes)
  249. ret, err = time.Parse("0601021504Z0700", s)
  250. if err != nil {
  251. ret, err = time.Parse("060102150405Z0700", s)
  252. }
  253. if err == nil && ret.Year() >= 2050 {
  254. // UTCTime only encodes times prior to 2050. See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1
  255. ret = ret.AddDate(-100, 0, 0)
  256. }
  257. return
  258. }
  259. // parseGeneralizedTime parses the GeneralizedTime from the given byte slice
  260. // and returns the resulting time.
  261. func parseGeneralizedTime(bytes []byte) (ret time.Time, err error) {
  262. return time.Parse("20060102150405Z0700", string(bytes))
  263. }
  264. // PrintableString
  265. // parsePrintableString parses a ASN.1 PrintableString from the given byte
  266. // array and returns it.
  267. func parsePrintableString(bytes []byte) (ret string, err error) {
  268. for _, b := range bytes {
  269. if !isPrintable(b) {
  270. err = SyntaxError{"PrintableString contains invalid character"}
  271. return
  272. }
  273. }
  274. ret = string(bytes)
  275. return
  276. }
  277. // isPrintable returns true iff the given b is in the ASN.1 PrintableString set.
  278. func isPrintable(b byte) bool {
  279. return 'a' <= b && b <= 'z' ||
  280. 'A' <= b && b <= 'Z' ||
  281. '0' <= b && b <= '9' ||
  282. '\'' <= b && b <= ')' ||
  283. '+' <= b && b <= '/' ||
  284. b == ' ' ||
  285. b == ':' ||
  286. b == '=' ||
  287. b == '?' ||
  288. // This is technically not allowed in a PrintableString.
  289. // However, x509 certificates with wildcard strings don't
  290. // always use the correct string type so we permit it.
  291. b == '*'
  292. }
  293. // IA5String
  294. // parseIA5String parses a ASN.1 IA5String (ASCII string) from the given
  295. // byte slice and returns it.
  296. func parseIA5String(bytes []byte) (ret string, err error) {
  297. for _, b := range bytes {
  298. if b >= 0x80 {
  299. err = SyntaxError{"IA5String contains invalid character"}
  300. return
  301. }
  302. }
  303. ret = string(bytes)
  304. return
  305. }
  306. // T61String
  307. // parseT61String parses a ASN.1 T61String (8-bit clean string) from the given
  308. // byte slice and returns it.
  309. func parseT61String(bytes []byte) (ret string, err error) {
  310. return string(bytes), nil
  311. }
  312. // UTF8String
  313. // parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte
  314. // array and returns it.
  315. func parseUTF8String(bytes []byte) (ret string, err error) {
  316. return string(bytes), nil
  317. }
  318. // A RawValue represents an undecoded ASN.1 object.
  319. type RawValue struct {
  320. Class, Tag int
  321. IsCompound bool
  322. Bytes []byte
  323. FullBytes []byte // includes the tag and length
  324. }
  325. // RawContent is used to signal that the undecoded, DER data needs to be
  326. // preserved for a struct. To use it, the first field of the struct must have
  327. // this type. It's an error for any of the other fields to have this type.
  328. type RawContent []byte
  329. // Tagging
  330. // parseTagAndLength parses an ASN.1 tag and length pair from the given offset
  331. // into a byte slice. It returns the parsed data and the new offset. SET and
  332. // SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we
  333. // don't distinguish between ordered and unordered objects in this code.
  334. func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) {
  335. offset = initOffset
  336. b := bytes[offset]
  337. offset++
  338. ret.class = int(b >> 6)
  339. ret.isCompound = b&0x20 == 0x20
  340. ret.tag = int(b & 0x1f)
  341. // If the bottom five bits are set, then the tag number is actually base 128
  342. // encoded afterwards
  343. if ret.tag == 0x1f {
  344. ret.tag, offset, err = parseBase128Int(bytes, offset)
  345. if err != nil {
  346. return
  347. }
  348. }
  349. if offset >= len(bytes) {
  350. err = SyntaxError{"truncated tag or length"}
  351. return
  352. }
  353. b = bytes[offset]
  354. offset++
  355. if b&0x80 == 0 {
  356. // The length is encoded in the bottom 7 bits.
  357. ret.length = int(b & 0x7f)
  358. } else {
  359. // Bottom 7 bits give the number of length bytes to follow.
  360. numBytes := int(b & 0x7f)
  361. if numBytes == 0 {
  362. err = SyntaxError{"indefinite length found (not DER)"}
  363. return
  364. }
  365. ret.length = 0
  366. for i := 0; i < numBytes; i++ {
  367. if offset >= len(bytes) {
  368. err = SyntaxError{"truncated tag or length"}
  369. return
  370. }
  371. b = bytes[offset]
  372. offset++
  373. if ret.length >= 1<<23 {
  374. // We can't shift ret.length up without
  375. // overflowing.
  376. err = StructuralError{"length too large"}
  377. return
  378. }
  379. ret.length <<= 8
  380. ret.length |= int(b)
  381. if ret.length == 0 {
  382. // DER requires that lengths be minimal.
  383. err = StructuralError{"superfluous leading zeros in length"}
  384. return
  385. }
  386. }
  387. }
  388. return
  389. }
  390. // parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse
  391. // a number of ASN.1 values from the given byte slice and returns them as a
  392. // slice of Go values of the given type.
  393. func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) {
  394. expectedTag, compoundType, ok := getUniversalType(elemType)
  395. if !ok {
  396. err = StructuralError{"unknown Go type for slice"}
  397. return
  398. }
  399. // First we iterate over the input and count the number of elements,
  400. // checking that the types are correct in each case.
  401. numElements := 0
  402. for offset := 0; offset < len(bytes); {
  403. var t tagAndLength
  404. t, offset, err = parseTagAndLength(bytes, offset)
  405. if err != nil {
  406. return
  407. }
  408. // We pretend that GENERAL STRINGs are PRINTABLE STRINGs so
  409. // that a sequence of them can be parsed into a []string.
  410. if t.tag == tagGeneralString {
  411. t.tag = tagPrintableString
  412. }
  413. if t.class != classUniversal || t.isCompound != compoundType || t.tag != expectedTag {
  414. err = StructuralError{"sequence tag mismatch"}
  415. return
  416. }
  417. if invalidLength(offset, t.length, len(bytes)) {
  418. err = SyntaxError{"truncated sequence"}
  419. return
  420. }
  421. offset += t.length
  422. numElements++
  423. }
  424. ret = reflect.MakeSlice(sliceType, numElements, numElements)
  425. params := fieldParameters{}
  426. offset := 0
  427. for i := 0; i < numElements; i++ {
  428. offset, err = parseField(ret.Index(i), bytes, offset, params)
  429. if err != nil {
  430. return
  431. }
  432. }
  433. return
  434. }
  435. var (
  436. bitStringType = reflect.TypeOf(BitString{})
  437. objectIdentifierType = reflect.TypeOf(ObjectIdentifier{})
  438. enumeratedType = reflect.TypeOf(Enumerated(0))
  439. flagType = reflect.TypeOf(Flag(false))
  440. timeType = reflect.TypeOf(time.Time{})
  441. rawValueType = reflect.TypeOf(RawValue{})
  442. rawContentsType = reflect.TypeOf(RawContent(nil))
  443. bigIntType = reflect.TypeOf(new(big.Int))
  444. )
  445. // invalidLength returns true iff offset + length > sliceLength, or if the
  446. // addition would overflow.
  447. func invalidLength(offset, length, sliceLength int) bool {
  448. return offset+length < offset || offset+length > sliceLength
  449. }
  450. // START CT CHANGES
  451. // Tests whether the data in |bytes| would be a valid ISO8859-1 string.
  452. // Clearly, a sequence of bytes comprised solely of valid ISO8859-1
  453. // codepoints does not imply that the encoding MUST be ISO8859-1, rather that
  454. // you would not encounter an error trying to interpret the data as such.
  455. func couldBeISO8859_1(bytes []byte) bool {
  456. for _, b := range bytes {
  457. if b < 0x20 || (b >= 0x7F && b < 0xA0) {
  458. return false
  459. }
  460. }
  461. return true
  462. }
  463. // Checks whether the data in |bytes| would be a valid T.61 string.
  464. // Clearly, a sequence of bytes comprised solely of valid T.61
  465. // codepoints does not imply that the encoding MUST be T.61, rather that
  466. // you would not encounter an error trying to interpret the data as such.
  467. func couldBeT61(bytes []byte) bool {
  468. for _, b := range bytes {
  469. switch b {
  470. case 0x00:
  471. // Since we're guessing at (incorrect) encodings for a
  472. // PrintableString, we'll err on the side of caution and disallow
  473. // strings with a NUL in them, don't want to re-create a PayPal NUL
  474. // situation in monitors.
  475. fallthrough
  476. case 0x23, 0x24, 0x5C, 0x5E, 0x60, 0x7B, 0x7D, 0x7E, 0xA5, 0xA6, 0xAC, 0xAD, 0xAE, 0xAF,
  477. 0xB9, 0xBA, 0xC0, 0xC9, 0xD0, 0xD1, 0xD2, 0xD3, 0xD4, 0xD5, 0xD6, 0xD7, 0xD8, 0xD9,
  478. 0xDA, 0xDB, 0xDC, 0xDE, 0xDF, 0xE5, 0xFF:
  479. // These are all invalid code points in T.61, so it can't be a T.61 string.
  480. return false
  481. }
  482. }
  483. return true
  484. }
  485. // Converts the data in |bytes| to the equivalent UTF-8 string.
  486. func iso8859_1ToUTF8(bytes []byte) string {
  487. buf := make([]rune, len(bytes))
  488. for i, b := range bytes {
  489. buf[i] = rune(b)
  490. }
  491. return string(buf)
  492. }
  493. // END CT CHANGES
  494. // parseField is the main parsing function. Given a byte slice and an offset
  495. // into the array, it will try to parse a suitable ASN.1 value out and store it
  496. // in the given Value.
  497. func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) {
  498. offset = initOffset
  499. fieldType := v.Type()
  500. // If we have run out of data, it may be that there are optional elements at the end.
  501. if offset == len(bytes) {
  502. if !setDefaultValue(v, params) {
  503. err = SyntaxError{"sequence truncated"}
  504. }
  505. return
  506. }
  507. // Deal with raw values.
  508. if fieldType == rawValueType {
  509. var t tagAndLength
  510. t, offset, err = parseTagAndLength(bytes, offset)
  511. if err != nil {
  512. return
  513. }
  514. if invalidLength(offset, t.length, len(bytes)) {
  515. err = SyntaxError{"data truncated"}
  516. return
  517. }
  518. result := RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length], bytes[initOffset : offset+t.length]}
  519. offset += t.length
  520. v.Set(reflect.ValueOf(result))
  521. return
  522. }
  523. // Deal with the ANY type.
  524. if ifaceType := fieldType; ifaceType.Kind() == reflect.Interface && ifaceType.NumMethod() == 0 {
  525. var t tagAndLength
  526. t, offset, err = parseTagAndLength(bytes, offset)
  527. if err != nil {
  528. return
  529. }
  530. if invalidLength(offset, t.length, len(bytes)) {
  531. err = SyntaxError{"data truncated"}
  532. return
  533. }
  534. var result interface{}
  535. if !t.isCompound && t.class == classUniversal {
  536. innerBytes := bytes[offset : offset+t.length]
  537. switch t.tag {
  538. case tagPrintableString:
  539. result, err = parsePrintableString(innerBytes)
  540. // START CT CHANGES
  541. if err != nil && strings.Contains(err.Error(), "PrintableString contains invalid character") {
  542. // Probably an ISO8859-1 string stuffed in, check if it
  543. // would be valid and assume that's what's happened if so,
  544. // otherwise try T.61, failing that give up and just assign
  545. // the bytes
  546. switch {
  547. case couldBeISO8859_1(innerBytes):
  548. result, err = iso8859_1ToUTF8(innerBytes), nil
  549. case couldBeT61(innerBytes):
  550. result, err = parseT61String(innerBytes)
  551. default:
  552. result = nil
  553. err = errors.New("PrintableString contains invalid character, but couldn't determine correct String type.")
  554. }
  555. }
  556. // END CT CHANGES
  557. case tagIA5String:
  558. result, err = parseIA5String(innerBytes)
  559. case tagT61String:
  560. result, err = parseT61String(innerBytes)
  561. case tagUTF8String:
  562. result, err = parseUTF8String(innerBytes)
  563. case tagInteger:
  564. result, err = parseInt64(innerBytes)
  565. case tagBitString:
  566. result, err = parseBitString(innerBytes)
  567. case tagOID:
  568. result, err = parseObjectIdentifier(innerBytes)
  569. case tagUTCTime:
  570. result, err = parseUTCTime(innerBytes)
  571. case tagOctetString:
  572. result = innerBytes
  573. default:
  574. // If we don't know how to handle the type, we just leave Value as nil.
  575. }
  576. }
  577. offset += t.length
  578. if err != nil {
  579. return
  580. }
  581. if result != nil {
  582. v.Set(reflect.ValueOf(result))
  583. }
  584. return
  585. }
  586. universalTag, compoundType, ok1 := getUniversalType(fieldType)
  587. if !ok1 {
  588. err = StructuralError{fmt.Sprintf("unknown Go type: %v", fieldType)}
  589. return
  590. }
  591. t, offset, err := parseTagAndLength(bytes, offset)
  592. if err != nil {
  593. return
  594. }
  595. if params.explicit {
  596. expectedClass := classContextSpecific
  597. if params.application {
  598. expectedClass = classApplication
  599. }
  600. if t.class == expectedClass && t.tag == *params.tag && (t.length == 0 || t.isCompound) {
  601. if t.length > 0 {
  602. t, offset, err = parseTagAndLength(bytes, offset)
  603. if err != nil {
  604. return
  605. }
  606. } else {
  607. if fieldType != flagType {
  608. err = StructuralError{"zero length explicit tag was not an asn1.Flag"}
  609. return
  610. }
  611. v.SetBool(true)
  612. return
  613. }
  614. } else {
  615. // The tags didn't match, it might be an optional element.
  616. ok := setDefaultValue(v, params)
  617. if ok {
  618. offset = initOffset
  619. } else {
  620. err = StructuralError{"explicitly tagged member didn't match"}
  621. }
  622. return
  623. }
  624. }
  625. // Special case for strings: all the ASN.1 string types map to the Go
  626. // type string. getUniversalType returns the tag for PrintableString
  627. // when it sees a string, so if we see a different string type on the
  628. // wire, we change the universal type to match.
  629. if universalTag == tagPrintableString {
  630. switch t.tag {
  631. case tagIA5String, tagGeneralString, tagT61String, tagUTF8String:
  632. universalTag = t.tag
  633. }
  634. }
  635. // Special case for time: UTCTime and GeneralizedTime both map to the
  636. // Go type time.Time.
  637. if universalTag == tagUTCTime && t.tag == tagGeneralizedTime {
  638. universalTag = tagGeneralizedTime
  639. }
  640. expectedClass := classUniversal
  641. expectedTag := universalTag
  642. if !params.explicit && params.tag != nil {
  643. expectedClass = classContextSpecific
  644. expectedTag = *params.tag
  645. }
  646. if !params.explicit && params.application && params.tag != nil {
  647. expectedClass = classApplication
  648. expectedTag = *params.tag
  649. }
  650. // We have unwrapped any explicit tagging at this point.
  651. if t.class != expectedClass || t.tag != expectedTag || t.isCompound != compoundType {
  652. // Tags don't match. Again, it could be an optional element.
  653. ok := setDefaultValue(v, params)
  654. if ok {
  655. offset = initOffset
  656. } else {
  657. err = StructuralError{fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)}
  658. }
  659. return
  660. }
  661. if invalidLength(offset, t.length, len(bytes)) {
  662. err = SyntaxError{"data truncated"}
  663. return
  664. }
  665. innerBytes := bytes[offset : offset+t.length]
  666. offset += t.length
  667. // We deal with the structures defined in this package first.
  668. switch fieldType {
  669. case objectIdentifierType:
  670. newSlice, err1 := parseObjectIdentifier(innerBytes)
  671. v.Set(reflect.MakeSlice(v.Type(), len(newSlice), len(newSlice)))
  672. if err1 == nil {
  673. reflect.Copy(v, reflect.ValueOf(newSlice))
  674. }
  675. err = err1
  676. return
  677. case bitStringType:
  678. bs, err1 := parseBitString(innerBytes)
  679. if err1 == nil {
  680. v.Set(reflect.ValueOf(bs))
  681. }
  682. err = err1
  683. return
  684. case timeType:
  685. var time time.Time
  686. var err1 error
  687. if universalTag == tagUTCTime {
  688. time, err1 = parseUTCTime(innerBytes)
  689. } else {
  690. time, err1 = parseGeneralizedTime(innerBytes)
  691. }
  692. if err1 == nil {
  693. v.Set(reflect.ValueOf(time))
  694. }
  695. err = err1
  696. return
  697. case enumeratedType:
  698. parsedInt, err1 := parseInt32(innerBytes)
  699. if err1 == nil {
  700. v.SetInt(int64(parsedInt))
  701. }
  702. err = err1
  703. return
  704. case flagType:
  705. v.SetBool(true)
  706. return
  707. case bigIntType:
  708. parsedInt := parseBigInt(innerBytes)
  709. v.Set(reflect.ValueOf(parsedInt))
  710. return
  711. }
  712. switch val := v; val.Kind() {
  713. case reflect.Bool:
  714. parsedBool, err1 := parseBool(innerBytes)
  715. if err1 == nil {
  716. val.SetBool(parsedBool)
  717. }
  718. err = err1
  719. return
  720. case reflect.Int, reflect.Int32, reflect.Int64:
  721. if val.Type().Size() == 4 {
  722. parsedInt, err1 := parseInt32(innerBytes)
  723. if err1 == nil {
  724. val.SetInt(int64(parsedInt))
  725. }
  726. err = err1
  727. } else {
  728. parsedInt, err1 := parseInt64(innerBytes)
  729. if err1 == nil {
  730. val.SetInt(parsedInt)
  731. }
  732. err = err1
  733. }
  734. return
  735. // TODO(dfc) Add support for the remaining integer types
  736. case reflect.Struct:
  737. structType := fieldType
  738. if structType.NumField() > 0 &&
  739. structType.Field(0).Type == rawContentsType {
  740. bytes := bytes[initOffset:offset]
  741. val.Field(0).Set(reflect.ValueOf(RawContent(bytes)))
  742. }
  743. innerOffset := 0
  744. for i := 0; i < structType.NumField(); i++ {
  745. field := structType.Field(i)
  746. if i == 0 && field.Type == rawContentsType {
  747. continue
  748. }
  749. innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag.Get("asn1")))
  750. if err != nil {
  751. return
  752. }
  753. }
  754. // We allow extra bytes at the end of the SEQUENCE because
  755. // adding elements to the end has been used in X.509 as the
  756. // version numbers have increased.
  757. return
  758. case reflect.Slice:
  759. sliceType := fieldType
  760. if sliceType.Elem().Kind() == reflect.Uint8 {
  761. val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes)))
  762. reflect.Copy(val, reflect.ValueOf(innerBytes))
  763. return
  764. }
  765. newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem())
  766. if err1 == nil {
  767. val.Set(newSlice)
  768. }
  769. err = err1
  770. return
  771. case reflect.String:
  772. var v string
  773. switch universalTag {
  774. case tagPrintableString:
  775. v, err = parsePrintableString(innerBytes)
  776. case tagIA5String:
  777. v, err = parseIA5String(innerBytes)
  778. case tagT61String:
  779. v, err = parseT61String(innerBytes)
  780. case tagUTF8String:
  781. v, err = parseUTF8String(innerBytes)
  782. case tagGeneralString:
  783. // GeneralString is specified in ISO-2022/ECMA-35,
  784. // A brief review suggests that it includes structures
  785. // that allow the encoding to change midstring and
  786. // such. We give up and pass it as an 8-bit string.
  787. v, err = parseT61String(innerBytes)
  788. default:
  789. err = SyntaxError{fmt.Sprintf("internal error: unknown string type %d", universalTag)}
  790. }
  791. if err == nil {
  792. val.SetString(v)
  793. }
  794. return
  795. }
  796. err = StructuralError{"unsupported: " + v.Type().String()}
  797. return
  798. }
  799. // setDefaultValue is used to install a default value, from a tag string, into
  800. // a Value. It is successful is the field was optional, even if a default value
  801. // wasn't provided or it failed to install it into the Value.
  802. func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) {
  803. if !params.optional {
  804. return
  805. }
  806. ok = true
  807. if params.defaultValue == nil {
  808. return
  809. }
  810. switch val := v; val.Kind() {
  811. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  812. val.SetInt(*params.defaultValue)
  813. }
  814. return
  815. }
  816. // Unmarshal parses the DER-encoded ASN.1 data structure b
  817. // and uses the reflect package to fill in an arbitrary value pointed at by val.
  818. // Because Unmarshal uses the reflect package, the structs
  819. // being written to must use upper case field names.
  820. //
  821. // An ASN.1 INTEGER can be written to an int, int32, int64,
  822. // or *big.Int (from the math/big package).
  823. // If the encoded value does not fit in the Go type,
  824. // Unmarshal returns a parse error.
  825. //
  826. // An ASN.1 BIT STRING can be written to a BitString.
  827. //
  828. // An ASN.1 OCTET STRING can be written to a []byte.
  829. //
  830. // An ASN.1 OBJECT IDENTIFIER can be written to an
  831. // ObjectIdentifier.
  832. //
  833. // An ASN.1 ENUMERATED can be written to an Enumerated.
  834. //
  835. // An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time.
  836. //
  837. // An ASN.1 PrintableString or IA5String can be written to a string.
  838. //
  839. // Any of the above ASN.1 values can be written to an interface{}.
  840. // The value stored in the interface has the corresponding Go type.
  841. // For integers, that type is int64.
  842. //
  843. // An ASN.1 SEQUENCE OF x or SET OF x can be written
  844. // to a slice if an x can be written to the slice's element type.
  845. //
  846. // An ASN.1 SEQUENCE or SET can be written to a struct
  847. // if each of the elements in the sequence can be
  848. // written to the corresponding element in the struct.
  849. //
  850. // The following tags on struct fields have special meaning to Unmarshal:
  851. //
  852. // optional marks the field as ASN.1 OPTIONAL
  853. // [explicit] tag:x specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC
  854. // default:x sets the default value for optional integer fields
  855. //
  856. // If the type of the first field of a structure is RawContent then the raw
  857. // ASN1 contents of the struct will be stored in it.
  858. //
  859. // Other ASN.1 types are not supported; if it encounters them,
  860. // Unmarshal returns a parse error.
  861. func Unmarshal(b []byte, val interface{}) (rest []byte, err error) {
  862. return UnmarshalWithParams(b, val, "")
  863. }
  864. // UnmarshalWithParams allows field parameters to be specified for the
  865. // top-level element. The form of the params is the same as the field tags.
  866. func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) {
  867. v := reflect.ValueOf(val).Elem()
  868. offset, err := parseField(v, b, 0, parseFieldParameters(params))
  869. if err != nil {
  870. return nil, err
  871. }
  872. return b[offset:], nil
  873. }