marshal.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "math/big"
  11. "reflect"
  12. "time"
  13. "unicode/utf8"
  14. )
  15. // A forkableWriter is an in-memory buffer that can be
  16. // 'forked' to create new forkableWriters that bracket the
  17. // original. After
  18. // pre, post := w.fork()
  19. // the overall sequence of bytes represented is logically w+pre+post.
  20. type forkableWriter struct {
  21. *bytes.Buffer
  22. pre, post *forkableWriter
  23. }
  24. func newForkableWriter() *forkableWriter {
  25. return &forkableWriter{new(bytes.Buffer), nil, nil}
  26. }
  27. func (f *forkableWriter) fork() (pre, post *forkableWriter) {
  28. if f.pre != nil || f.post != nil {
  29. panic("have already forked")
  30. }
  31. f.pre = newForkableWriter()
  32. f.post = newForkableWriter()
  33. return f.pre, f.post
  34. }
  35. func (f *forkableWriter) Len() (l int) {
  36. l += f.Buffer.Len()
  37. if f.pre != nil {
  38. l += f.pre.Len()
  39. }
  40. if f.post != nil {
  41. l += f.post.Len()
  42. }
  43. return
  44. }
  45. func (f *forkableWriter) writeTo(out io.Writer) (n int, err error) {
  46. n, err = out.Write(f.Bytes())
  47. if err != nil {
  48. return
  49. }
  50. var nn int
  51. if f.pre != nil {
  52. nn, err = f.pre.writeTo(out)
  53. n += nn
  54. if err != nil {
  55. return
  56. }
  57. }
  58. if f.post != nil {
  59. nn, err = f.post.writeTo(out)
  60. n += nn
  61. }
  62. return
  63. }
  64. func marshalBase128Int(out *forkableWriter, n int64) (err error) {
  65. if n == 0 {
  66. err = out.WriteByte(0)
  67. return
  68. }
  69. l := 0
  70. for i := n; i > 0; i >>= 7 {
  71. l++
  72. }
  73. for i := l - 1; i >= 0; i-- {
  74. o := byte(n >> uint(i*7))
  75. o &= 0x7f
  76. if i != 0 {
  77. o |= 0x80
  78. }
  79. err = out.WriteByte(o)
  80. if err != nil {
  81. return
  82. }
  83. }
  84. return nil
  85. }
  86. func marshalInt64(out *forkableWriter, i int64) (err error) {
  87. n := int64Length(i)
  88. for ; n > 0; n-- {
  89. err = out.WriteByte(byte(i >> uint((n-1)*8)))
  90. if err != nil {
  91. return
  92. }
  93. }
  94. return nil
  95. }
  96. func int64Length(i int64) (numBytes int) {
  97. numBytes = 1
  98. for i > 127 {
  99. numBytes++
  100. i >>= 8
  101. }
  102. for i < -128 {
  103. numBytes++
  104. i >>= 8
  105. }
  106. return
  107. }
  108. func marshalBigInt(out *forkableWriter, n *big.Int) (err error) {
  109. if n.Sign() < 0 {
  110. // A negative number has to be converted to two's-complement
  111. // form. So we'll subtract 1 and invert. If the
  112. // most-significant-bit isn't set then we'll need to pad the
  113. // beginning with 0xff in order to keep the number negative.
  114. nMinus1 := new(big.Int).Neg(n)
  115. nMinus1.Sub(nMinus1, bigOne)
  116. bytes := nMinus1.Bytes()
  117. for i := range bytes {
  118. bytes[i] ^= 0xff
  119. }
  120. if len(bytes) == 0 || bytes[0]&0x80 == 0 {
  121. err = out.WriteByte(0xff)
  122. if err != nil {
  123. return
  124. }
  125. }
  126. _, err = out.Write(bytes)
  127. } else if n.Sign() == 0 {
  128. // Zero is written as a single 0 zero rather than no bytes.
  129. err = out.WriteByte(0x00)
  130. } else {
  131. bytes := n.Bytes()
  132. if len(bytes) > 0 && bytes[0]&0x80 != 0 {
  133. // We'll have to pad this with 0x00 in order to stop it
  134. // looking like a negative number.
  135. err = out.WriteByte(0)
  136. if err != nil {
  137. return
  138. }
  139. }
  140. _, err = out.Write(bytes)
  141. }
  142. return
  143. }
  144. func marshalLength(out *forkableWriter, i int) (err error) {
  145. n := lengthLength(i)
  146. for ; n > 0; n-- {
  147. err = out.WriteByte(byte(i >> uint((n-1)*8)))
  148. if err != nil {
  149. return
  150. }
  151. }
  152. return nil
  153. }
  154. func lengthLength(i int) (numBytes int) {
  155. numBytes = 1
  156. for i > 255 {
  157. numBytes++
  158. i >>= 8
  159. }
  160. return
  161. }
  162. func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err error) {
  163. b := uint8(t.class) << 6
  164. if t.isCompound {
  165. b |= 0x20
  166. }
  167. if t.tag >= 31 {
  168. b |= 0x1f
  169. err = out.WriteByte(b)
  170. if err != nil {
  171. return
  172. }
  173. err = marshalBase128Int(out, int64(t.tag))
  174. if err != nil {
  175. return
  176. }
  177. } else {
  178. b |= uint8(t.tag)
  179. err = out.WriteByte(b)
  180. if err != nil {
  181. return
  182. }
  183. }
  184. if t.length >= 128 {
  185. l := lengthLength(t.length)
  186. err = out.WriteByte(0x80 | byte(l))
  187. if err != nil {
  188. return
  189. }
  190. err = marshalLength(out, t.length)
  191. if err != nil {
  192. return
  193. }
  194. } else {
  195. err = out.WriteByte(byte(t.length))
  196. if err != nil {
  197. return
  198. }
  199. }
  200. return nil
  201. }
  202. func marshalBitString(out *forkableWriter, b BitString) (err error) {
  203. paddingBits := byte((8 - b.BitLength%8) % 8)
  204. err = out.WriteByte(paddingBits)
  205. if err != nil {
  206. return
  207. }
  208. _, err = out.Write(b.Bytes)
  209. return
  210. }
  211. func marshalObjectIdentifier(out *forkableWriter, oid []int) (err error) {
  212. if len(oid) < 2 || oid[0] > 2 || (oid[0] < 2 && oid[1] >= 40) {
  213. return StructuralError{"invalid object identifier"}
  214. }
  215. err = marshalBase128Int(out, int64(oid[0]*40+oid[1]))
  216. if err != nil {
  217. return
  218. }
  219. for i := 2; i < len(oid); i++ {
  220. err = marshalBase128Int(out, int64(oid[i]))
  221. if err != nil {
  222. return
  223. }
  224. }
  225. return
  226. }
  227. func marshalPrintableString(out *forkableWriter, s string) (err error) {
  228. b := []byte(s)
  229. for _, c := range b {
  230. if !isPrintable(c) {
  231. return StructuralError{"PrintableString contains invalid character"}
  232. }
  233. }
  234. _, err = out.Write(b)
  235. return
  236. }
  237. func marshalIA5String(out *forkableWriter, s string) (err error) {
  238. b := []byte(s)
  239. for _, c := range b {
  240. if c > 127 {
  241. return StructuralError{"IA5String contains invalid character"}
  242. }
  243. }
  244. _, err = out.Write(b)
  245. return
  246. }
  247. func marshalUTF8String(out *forkableWriter, s string) (err error) {
  248. _, err = out.Write([]byte(s))
  249. return
  250. }
  251. func marshalTwoDigits(out *forkableWriter, v int) (err error) {
  252. err = out.WriteByte(byte('0' + (v/10)%10))
  253. if err != nil {
  254. return
  255. }
  256. return out.WriteByte(byte('0' + v%10))
  257. }
  258. func marshalFourDigits(out *forkableWriter, v int) (err error) {
  259. var bytes [4]byte
  260. for i := range bytes {
  261. bytes[3-i] = '0' + byte(v%10)
  262. v /= 10
  263. }
  264. _, err = out.Write(bytes[:])
  265. return
  266. }
  267. func outsideUTCRange(t time.Time) bool {
  268. year := t.Year()
  269. return year < 1950 || year >= 2050
  270. }
  271. func marshalUTCTime(out *forkableWriter, t time.Time) (err error) {
  272. year := t.Year()
  273. switch {
  274. case 1950 <= year && year < 2000:
  275. err = marshalTwoDigits(out, year-1900)
  276. case 2000 <= year && year < 2050:
  277. err = marshalTwoDigits(out, year-2000)
  278. default:
  279. return StructuralError{"cannot represent time as UTCTime"}
  280. }
  281. if err != nil {
  282. return
  283. }
  284. return marshalTimeCommon(out, t)
  285. }
  286. func marshalGeneralizedTime(out *forkableWriter, t time.Time) (err error) {
  287. year := t.Year()
  288. if year < 0 || year > 9999 {
  289. return StructuralError{"cannot represent time as GeneralizedTime"}
  290. }
  291. if err = marshalFourDigits(out, year); err != nil {
  292. return
  293. }
  294. return marshalTimeCommon(out, t)
  295. }
  296. func marshalTimeCommon(out *forkableWriter, t time.Time) (err error) {
  297. _, month, day := t.Date()
  298. err = marshalTwoDigits(out, int(month))
  299. if err != nil {
  300. return
  301. }
  302. err = marshalTwoDigits(out, day)
  303. if err != nil {
  304. return
  305. }
  306. hour, min, sec := t.Clock()
  307. err = marshalTwoDigits(out, hour)
  308. if err != nil {
  309. return
  310. }
  311. err = marshalTwoDigits(out, min)
  312. if err != nil {
  313. return
  314. }
  315. err = marshalTwoDigits(out, sec)
  316. if err != nil {
  317. return
  318. }
  319. _, offset := t.Zone()
  320. switch {
  321. case offset/60 == 0:
  322. err = out.WriteByte('Z')
  323. return
  324. case offset > 0:
  325. err = out.WriteByte('+')
  326. case offset < 0:
  327. err = out.WriteByte('-')
  328. }
  329. if err != nil {
  330. return
  331. }
  332. offsetMinutes := offset / 60
  333. if offsetMinutes < 0 {
  334. offsetMinutes = -offsetMinutes
  335. }
  336. err = marshalTwoDigits(out, offsetMinutes/60)
  337. if err != nil {
  338. return
  339. }
  340. err = marshalTwoDigits(out, offsetMinutes%60)
  341. return
  342. }
  343. func stripTagAndLength(in []byte) []byte {
  344. _, offset, err := parseTagAndLength(in, 0)
  345. if err != nil {
  346. return in
  347. }
  348. return in[offset:]
  349. }
  350. func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameters) (err error) {
  351. switch value.Type() {
  352. case flagType:
  353. return nil
  354. case timeType:
  355. t := value.Interface().(time.Time)
  356. if params.timeType == TagGeneralizedTime || outsideUTCRange(t) {
  357. return marshalGeneralizedTime(out, t)
  358. } else {
  359. return marshalUTCTime(out, t)
  360. }
  361. case bitStringType:
  362. return marshalBitString(out, value.Interface().(BitString))
  363. case objectIdentifierType:
  364. return marshalObjectIdentifier(out, value.Interface().(ObjectIdentifier))
  365. case bigIntType:
  366. return marshalBigInt(out, value.Interface().(*big.Int))
  367. }
  368. switch v := value; v.Kind() {
  369. case reflect.Bool:
  370. if v.Bool() {
  371. return out.WriteByte(255)
  372. } else {
  373. return out.WriteByte(0)
  374. }
  375. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  376. return marshalInt64(out, v.Int())
  377. case reflect.Struct:
  378. t := v.Type()
  379. startingField := 0
  380. // If the first element of the structure is a non-empty
  381. // RawContents, then we don't bother serializing the rest.
  382. if t.NumField() > 0 && t.Field(0).Type == rawContentsType {
  383. s := v.Field(0)
  384. if s.Len() > 0 {
  385. bytes := make([]byte, s.Len())
  386. for i := 0; i < s.Len(); i++ {
  387. bytes[i] = uint8(s.Index(i).Uint())
  388. }
  389. /* The RawContents will contain the tag and
  390. * length fields but we'll also be writing
  391. * those ourselves, so we strip them out of
  392. * bytes */
  393. _, err = out.Write(stripTagAndLength(bytes))
  394. return
  395. } else {
  396. startingField = 1
  397. }
  398. }
  399. for i := startingField; i < t.NumField(); i++ {
  400. var pre *forkableWriter
  401. pre, out = out.fork()
  402. err = marshalField(pre, v.Field(i), parseFieldParameters(t.Field(i).Tag.Get("asn1")))
  403. if err != nil {
  404. return
  405. }
  406. }
  407. return
  408. case reflect.Slice:
  409. sliceType := v.Type()
  410. if sliceType.Elem().Kind() == reflect.Uint8 {
  411. bytes := make([]byte, v.Len())
  412. for i := 0; i < v.Len(); i++ {
  413. bytes[i] = uint8(v.Index(i).Uint())
  414. }
  415. _, err = out.Write(bytes)
  416. return
  417. }
  418. // jtasn1 Pass on the tags to the members but need to unset explicit switch and implicit value
  419. //var fp fieldParameters
  420. params.explicit = false
  421. params.tag = nil
  422. for i := 0; i < v.Len(); i++ {
  423. var pre *forkableWriter
  424. pre, out = out.fork()
  425. err = marshalField(pre, v.Index(i), params)
  426. if err != nil {
  427. return
  428. }
  429. }
  430. return
  431. case reflect.String:
  432. switch params.stringType {
  433. case TagIA5String:
  434. return marshalIA5String(out, v.String())
  435. case TagPrintableString:
  436. return marshalPrintableString(out, v.String())
  437. default:
  438. return marshalUTF8String(out, v.String())
  439. }
  440. }
  441. return StructuralError{"unknown Go type"}
  442. }
  443. func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters) (err error) {
  444. if !v.IsValid() {
  445. return fmt.Errorf("asn1: cannot marshal nil value")
  446. }
  447. // If the field is an interface{} then recurse into it.
  448. if v.Kind() == reflect.Interface && v.Type().NumMethod() == 0 {
  449. return marshalField(out, v.Elem(), params)
  450. }
  451. if v.Kind() == reflect.Slice && v.Len() == 0 && params.omitEmpty {
  452. return
  453. }
  454. if params.optional && params.defaultValue != nil && canHaveDefaultValue(v.Kind()) {
  455. defaultValue := reflect.New(v.Type()).Elem()
  456. defaultValue.SetInt(*params.defaultValue)
  457. if reflect.DeepEqual(v.Interface(), defaultValue.Interface()) {
  458. return
  459. }
  460. }
  461. // If no default value is given then the zero value for the type is
  462. // assumed to be the default value. This isn't obviously the correct
  463. // behaviour, but it's what Go has traditionally done.
  464. if params.optional && params.defaultValue == nil {
  465. if reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) {
  466. return
  467. }
  468. }
  469. if v.Type() == rawValueType {
  470. rv := v.Interface().(RawValue)
  471. if len(rv.FullBytes) != 0 {
  472. _, err = out.Write(rv.FullBytes)
  473. } else {
  474. err = marshalTagAndLength(out, tagAndLength{rv.Class, rv.Tag, len(rv.Bytes), rv.IsCompound})
  475. if err != nil {
  476. return
  477. }
  478. _, err = out.Write(rv.Bytes)
  479. }
  480. return
  481. }
  482. tag, isCompound, ok := getUniversalType(v.Type())
  483. if !ok {
  484. err = StructuralError{fmt.Sprintf("unknown Go type: %v", v.Type())}
  485. return
  486. }
  487. class := ClassUniversal
  488. if params.timeType != 0 && tag != TagUTCTime {
  489. return StructuralError{"explicit time type given to non-time member"}
  490. }
  491. // jtasn1 updated to allow slices of strings
  492. if params.stringType != 0 && !(tag == TagPrintableString || (v.Kind() == reflect.Slice && tag == 16 && v.Type().Elem().Kind() == reflect.String)) {
  493. return StructuralError{"explicit string type given to non-string member"}
  494. }
  495. switch tag {
  496. case TagPrintableString:
  497. if params.stringType == 0 {
  498. // This is a string without an explicit string type. We'll use
  499. // a PrintableString if the character set in the string is
  500. // sufficiently limited, otherwise we'll use a UTF8String.
  501. for _, r := range v.String() {
  502. if r >= utf8.RuneSelf || !isPrintable(byte(r)) {
  503. if !utf8.ValidString(v.String()) {
  504. return errors.New("asn1: string not valid UTF-8")
  505. }
  506. tag = TagUTF8String
  507. break
  508. }
  509. }
  510. } else {
  511. tag = params.stringType
  512. }
  513. case TagUTCTime:
  514. if params.timeType == TagGeneralizedTime || outsideUTCRange(v.Interface().(time.Time)) {
  515. tag = TagGeneralizedTime
  516. }
  517. }
  518. if params.set {
  519. if tag != TagSequence {
  520. return StructuralError{"non sequence tagged as set"}
  521. }
  522. tag = TagSet
  523. }
  524. tags, body := out.fork()
  525. err = marshalBody(body, v, params)
  526. if err != nil {
  527. return
  528. }
  529. bodyLen := body.Len()
  530. var explicitTag *forkableWriter
  531. if params.explicit {
  532. explicitTag, tags = tags.fork()
  533. }
  534. if !params.explicit && params.tag != nil {
  535. // implicit tag.
  536. tag = *params.tag
  537. class = ClassContextSpecific
  538. }
  539. err = marshalTagAndLength(tags, tagAndLength{class, tag, bodyLen, isCompound})
  540. if err != nil {
  541. return
  542. }
  543. if params.explicit {
  544. err = marshalTagAndLength(explicitTag, tagAndLength{
  545. class: ClassContextSpecific,
  546. tag: *params.tag,
  547. length: bodyLen + tags.Len(),
  548. isCompound: true,
  549. })
  550. }
  551. return err
  552. }
  553. // Marshal returns the ASN.1 encoding of val.
  554. //
  555. // In addition to the struct tags recognised by Unmarshal, the following can be
  556. // used:
  557. //
  558. // ia5: causes strings to be marshaled as ASN.1, IA5 strings
  559. // omitempty: causes empty slices to be skipped
  560. // printable: causes strings to be marshaled as ASN.1, PrintableString strings.
  561. // utf8: causes strings to be marshaled as ASN.1, UTF8 strings
  562. func Marshal(val interface{}) ([]byte, error) {
  563. var out bytes.Buffer
  564. v := reflect.ValueOf(val)
  565. f := newForkableWriter()
  566. err := marshalField(f, v, fieldParameters{})
  567. if err != nil {
  568. return nil, err
  569. }
  570. _, err = f.writeTo(&out)
  571. return out.Bytes(), err
  572. }