asn1.go 27 KB

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