serialization.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. package ct
  2. import (
  3. "bytes"
  4. "container/list"
  5. "crypto"
  6. "encoding/asn1"
  7. "encoding/binary"
  8. "encoding/json"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "strings"
  13. )
  14. // Variable size structure prefix-header byte lengths
  15. const (
  16. CertificateLengthBytes = 3
  17. PreCertificateLengthBytes = 3
  18. ExtensionsLengthBytes = 2
  19. CertificateChainLengthBytes = 3
  20. SignatureLengthBytes = 2
  21. JSONLengthBytes = 3
  22. )
  23. // Max lengths
  24. const (
  25. MaxCertificateLength = (1 << 24) - 1
  26. MaxExtensionsLength = (1 << 16) - 1
  27. MaxSCTInListLength = (1 << 16) - 1
  28. MaxSCTListLength = (1 << 16) - 1
  29. )
  30. func writeUint(w io.Writer, value uint64, numBytes int) error {
  31. buf := make([]uint8, numBytes)
  32. for i := 0; i < numBytes; i++ {
  33. buf[numBytes-i-1] = uint8(value & 0xff)
  34. value >>= 8
  35. }
  36. if value != 0 {
  37. return errors.New("numBytes was insufficiently large to represent value")
  38. }
  39. if _, err := w.Write(buf); err != nil {
  40. return err
  41. }
  42. return nil
  43. }
  44. func writeVarBytes(w io.Writer, value []byte, numLenBytes int) error {
  45. if err := writeUint(w, uint64(len(value)), numLenBytes); err != nil {
  46. return err
  47. }
  48. if _, err := w.Write(value); err != nil {
  49. return err
  50. }
  51. return nil
  52. }
  53. func readUint(r io.Reader, numBytes int) (uint64, error) {
  54. var l uint64
  55. for i := 0; i < numBytes; i++ {
  56. l <<= 8
  57. var t uint8
  58. if err := binary.Read(r, binary.BigEndian, &t); err != nil {
  59. return 0, err
  60. }
  61. l |= uint64(t)
  62. }
  63. return l, nil
  64. }
  65. // Reads a variable length array of bytes from |r|. |numLenBytes| specifies the
  66. // number of (BigEndian) prefix-bytes which contain the length of the actual
  67. // array data bytes that follow.
  68. // Allocates an array to hold the contents and returns a slice view into it if
  69. // the read was successful, or an error otherwise.
  70. func readVarBytes(r io.Reader, numLenBytes int) ([]byte, error) {
  71. switch {
  72. case numLenBytes > 8:
  73. return nil, fmt.Errorf("numLenBytes too large (%d)", numLenBytes)
  74. case numLenBytes == 0:
  75. return nil, errors.New("numLenBytes should be > 0")
  76. }
  77. l, err := readUint(r, numLenBytes)
  78. if err != nil {
  79. return nil, err
  80. }
  81. data := make([]byte, l)
  82. if n, err := io.ReadFull(r, data); err != nil {
  83. if err == io.EOF || err == io.ErrUnexpectedEOF {
  84. return nil, fmt.Errorf("short read: expected %d but got %d", l, n)
  85. }
  86. return nil, err
  87. }
  88. return data, nil
  89. }
  90. // Reads a list of ASN1Cert types from |r|
  91. func readASN1CertList(r io.Reader, totalLenBytes int, elementLenBytes int) ([]ASN1Cert, error) {
  92. listBytes, err := readVarBytes(r, totalLenBytes)
  93. if err != nil {
  94. return []ASN1Cert{}, err
  95. }
  96. list := list.New()
  97. listReader := bytes.NewReader(listBytes)
  98. var entry []byte
  99. for err == nil {
  100. entry, err = readVarBytes(listReader, elementLenBytes)
  101. if err != nil {
  102. if err != io.EOF {
  103. return []ASN1Cert{}, err
  104. }
  105. } else {
  106. list.PushBack(entry)
  107. }
  108. }
  109. ret := make([]ASN1Cert, list.Len())
  110. i := 0
  111. for e := list.Front(); e != nil; e = e.Next() {
  112. ret[i] = e.Value.([]byte)
  113. i++
  114. }
  115. return ret, nil
  116. }
  117. // ReadTimestampedEntryInto parses the byte-stream representation of a
  118. // TimestampedEntry from |r| and populates the struct |t| with the data. See
  119. // RFC section 3.4 for details on the format.
  120. // Returns a non-nil error if there was a problem.
  121. func ReadTimestampedEntryInto(r io.Reader, t *TimestampedEntry) error {
  122. var err error
  123. if err = binary.Read(r, binary.BigEndian, &t.Timestamp); err != nil {
  124. return err
  125. }
  126. if err = binary.Read(r, binary.BigEndian, &t.EntryType); err != nil {
  127. return err
  128. }
  129. switch t.EntryType {
  130. case X509LogEntryType:
  131. if t.X509Entry, err = readVarBytes(r, CertificateLengthBytes); err != nil {
  132. return err
  133. }
  134. case PrecertLogEntryType:
  135. if err := binary.Read(r, binary.BigEndian, &t.PrecertEntry.IssuerKeyHash); err != nil {
  136. return err
  137. }
  138. if t.PrecertEntry.TBSCertificate, err = readVarBytes(r, PreCertificateLengthBytes); err != nil {
  139. return err
  140. }
  141. case XJSONLogEntryType:
  142. if t.JSONData, err = readVarBytes(r, JSONLengthBytes); err != nil {
  143. return err
  144. }
  145. default:
  146. return fmt.Errorf("unknown EntryType: %d", t.EntryType)
  147. }
  148. t.Extensions, err = readVarBytes(r, ExtensionsLengthBytes)
  149. return nil
  150. }
  151. // SerializeTimestampedEntry writes timestamped entry to Writer.
  152. // In case of error, w may contain garbage.
  153. func SerializeTimestampedEntry(w io.Writer, t *TimestampedEntry) error {
  154. if err := binary.Write(w, binary.BigEndian, t.Timestamp); err != nil {
  155. return err
  156. }
  157. if err := binary.Write(w, binary.BigEndian, t.EntryType); err != nil {
  158. return err
  159. }
  160. switch t.EntryType {
  161. case X509LogEntryType:
  162. if err := writeVarBytes(w, t.X509Entry, CertificateLengthBytes); err != nil {
  163. return err
  164. }
  165. case PrecertLogEntryType:
  166. if err := binary.Write(w, binary.BigEndian, t.PrecertEntry.IssuerKeyHash); err != nil {
  167. return err
  168. }
  169. if err := writeVarBytes(w, t.PrecertEntry.TBSCertificate, PreCertificateLengthBytes); err != nil {
  170. return err
  171. }
  172. case XJSONLogEntryType:
  173. // TODO: Pending google/certificate-transparency#1243, replace
  174. // with ObjectHash once supported by CT server.
  175. //jsonhash := objecthash.CommonJSONHash(string(t.JSONData))
  176. if err := writeVarBytes(w, []byte(t.JSONData), JSONLengthBytes); err != nil {
  177. return err
  178. }
  179. default:
  180. return fmt.Errorf("unknown EntryType: %d", t.EntryType)
  181. }
  182. writeVarBytes(w, t.Extensions, ExtensionsLengthBytes)
  183. return nil
  184. }
  185. // ReadMerkleTreeLeaf parses the byte-stream representation of a MerkleTreeLeaf
  186. // and returns a pointer to a new MerkleTreeLeaf structure containing the
  187. // parsed data.
  188. // See RFC section 3.4 for details on the format.
  189. // Returns a pointer to a new MerkleTreeLeaf or non-nil error if there was a
  190. // problem
  191. func ReadMerkleTreeLeaf(r io.Reader) (*MerkleTreeLeaf, error) {
  192. var m MerkleTreeLeaf
  193. if err := binary.Read(r, binary.BigEndian, &m.Version); err != nil {
  194. return nil, err
  195. }
  196. if m.Version != V1 {
  197. return nil, fmt.Errorf("unknown Version %d", m.Version)
  198. }
  199. if err := binary.Read(r, binary.BigEndian, &m.LeafType); err != nil {
  200. return nil, err
  201. }
  202. if m.LeafType != TimestampedEntryLeafType {
  203. return nil, fmt.Errorf("unknown LeafType %d", m.LeafType)
  204. }
  205. if err := ReadTimestampedEntryInto(r, &m.TimestampedEntry); err != nil {
  206. return nil, err
  207. }
  208. return &m, nil
  209. }
  210. // UnmarshalX509ChainArray unmarshalls the contents of the "chain:" entry in a
  211. // GetEntries response in the case where the entry refers to an X509 leaf.
  212. func UnmarshalX509ChainArray(b []byte) ([]ASN1Cert, error) {
  213. return readASN1CertList(bytes.NewReader(b), CertificateChainLengthBytes, CertificateLengthBytes)
  214. }
  215. // UnmarshalPrecertChainArray unmarshalls the contents of the "chain:" entry in
  216. // a GetEntries response in the case where the entry refers to a Precertificate
  217. // leaf.
  218. func UnmarshalPrecertChainArray(b []byte) ([]ASN1Cert, error) {
  219. var chain []ASN1Cert
  220. reader := bytes.NewReader(b)
  221. // read the pre-cert entry:
  222. precert, err := readVarBytes(reader, CertificateLengthBytes)
  223. if err != nil {
  224. return chain, err
  225. }
  226. chain = append(chain, precert)
  227. // and then read and return the chain up to the root:
  228. remainingChain, err := readASN1CertList(reader, CertificateChainLengthBytes, CertificateLengthBytes)
  229. if err != nil {
  230. return chain, err
  231. }
  232. chain = append(chain, remainingChain...)
  233. return chain, nil
  234. }
  235. // UnmarshalDigitallySigned reconstructs a DigitallySigned structure from a Reader
  236. func UnmarshalDigitallySigned(r io.Reader) (*DigitallySigned, error) {
  237. var h byte
  238. if err := binary.Read(r, binary.BigEndian, &h); err != nil {
  239. return nil, fmt.Errorf("failed to read HashAlgorithm: %v", err)
  240. }
  241. var s byte
  242. if err := binary.Read(r, binary.BigEndian, &s); err != nil {
  243. return nil, fmt.Errorf("failed to read SignatureAlgorithm: %v", err)
  244. }
  245. sig, err := readVarBytes(r, SignatureLengthBytes)
  246. if err != nil {
  247. return nil, fmt.Errorf("failed to read Signature bytes: %v", err)
  248. }
  249. return &DigitallySigned{
  250. HashAlgorithm: HashAlgorithm(h),
  251. SignatureAlgorithm: SignatureAlgorithm(s),
  252. Signature: sig,
  253. }, nil
  254. }
  255. func marshalDigitallySignedHere(ds DigitallySigned, here []byte) ([]byte, error) {
  256. sigLen := len(ds.Signature)
  257. dsOutLen := 2 + SignatureLengthBytes + sigLen
  258. if here == nil {
  259. here = make([]byte, dsOutLen)
  260. }
  261. if len(here) < dsOutLen {
  262. return nil, ErrNotEnoughBuffer
  263. }
  264. here = here[0:dsOutLen]
  265. here[0] = byte(ds.HashAlgorithm)
  266. here[1] = byte(ds.SignatureAlgorithm)
  267. binary.BigEndian.PutUint16(here[2:4], uint16(sigLen))
  268. copy(here[4:], ds.Signature)
  269. return here, nil
  270. }
  271. // MarshalDigitallySigned marshalls a DigitallySigned structure into a byte array
  272. func MarshalDigitallySigned(ds DigitallySigned) ([]byte, error) {
  273. return marshalDigitallySignedHere(ds, nil)
  274. }
  275. func checkCertificateFormat(cert ASN1Cert) error {
  276. if len(cert) == 0 {
  277. return errors.New("certificate is zero length")
  278. }
  279. if len(cert) > MaxCertificateLength {
  280. return errors.New("certificate too large")
  281. }
  282. return nil
  283. }
  284. func checkExtensionsFormat(ext CTExtensions) error {
  285. if len(ext) > MaxExtensionsLength {
  286. return errors.New("extensions too large")
  287. }
  288. return nil
  289. }
  290. func serializeV1CertSCTSignatureInput(timestamp uint64, cert ASN1Cert, ext CTExtensions) ([]byte, error) {
  291. if err := checkCertificateFormat(cert); err != nil {
  292. return nil, err
  293. }
  294. if err := checkExtensionsFormat(ext); err != nil {
  295. return nil, err
  296. }
  297. var buf bytes.Buffer
  298. if err := binary.Write(&buf, binary.BigEndian, V1); err != nil {
  299. return nil, err
  300. }
  301. if err := binary.Write(&buf, binary.BigEndian, CertificateTimestampSignatureType); err != nil {
  302. return nil, err
  303. }
  304. if err := binary.Write(&buf, binary.BigEndian, timestamp); err != nil {
  305. return nil, err
  306. }
  307. if err := binary.Write(&buf, binary.BigEndian, X509LogEntryType); err != nil {
  308. return nil, err
  309. }
  310. if err := writeVarBytes(&buf, cert, CertificateLengthBytes); err != nil {
  311. return nil, err
  312. }
  313. if err := writeVarBytes(&buf, ext, ExtensionsLengthBytes); err != nil {
  314. return nil, err
  315. }
  316. return buf.Bytes(), nil
  317. }
  318. func serializeV1JSONSCTSignatureInput(timestamp uint64, j []byte) ([]byte, error) {
  319. var buf bytes.Buffer
  320. if err := binary.Write(&buf, binary.BigEndian, V1); err != nil {
  321. return nil, err
  322. }
  323. if err := binary.Write(&buf, binary.BigEndian, CertificateTimestampSignatureType); err != nil {
  324. return nil, err
  325. }
  326. if err := binary.Write(&buf, binary.BigEndian, timestamp); err != nil {
  327. return nil, err
  328. }
  329. if err := binary.Write(&buf, binary.BigEndian, XJSONLogEntryType); err != nil {
  330. return nil, err
  331. }
  332. if err := writeVarBytes(&buf, j, JSONLengthBytes); err != nil {
  333. return nil, err
  334. }
  335. if err := writeVarBytes(&buf, nil, ExtensionsLengthBytes); err != nil {
  336. return nil, err
  337. }
  338. return buf.Bytes(), nil
  339. }
  340. func serializeV1PrecertSCTSignatureInput(timestamp uint64, issuerKeyHash [issuerKeyHashLength]byte, tbs []byte, ext CTExtensions) ([]byte, error) {
  341. if err := checkCertificateFormat(tbs); err != nil {
  342. return nil, err
  343. }
  344. if err := checkExtensionsFormat(ext); err != nil {
  345. return nil, err
  346. }
  347. var buf bytes.Buffer
  348. if err := binary.Write(&buf, binary.BigEndian, V1); err != nil {
  349. return nil, err
  350. }
  351. if err := binary.Write(&buf, binary.BigEndian, CertificateTimestampSignatureType); err != nil {
  352. return nil, err
  353. }
  354. if err := binary.Write(&buf, binary.BigEndian, timestamp); err != nil {
  355. return nil, err
  356. }
  357. if err := binary.Write(&buf, binary.BigEndian, PrecertLogEntryType); err != nil {
  358. return nil, err
  359. }
  360. if _, err := buf.Write(issuerKeyHash[:]); err != nil {
  361. return nil, err
  362. }
  363. if err := writeVarBytes(&buf, tbs, CertificateLengthBytes); err != nil {
  364. return nil, err
  365. }
  366. if err := writeVarBytes(&buf, ext, ExtensionsLengthBytes); err != nil {
  367. return nil, err
  368. }
  369. return buf.Bytes(), nil
  370. }
  371. func serializeV1SCTSignatureInput(sct SignedCertificateTimestamp, entry LogEntry) ([]byte, error) {
  372. if sct.SCTVersion != V1 {
  373. return nil, fmt.Errorf("unsupported SCT version, expected V1, but got %s", sct.SCTVersion)
  374. }
  375. if entry.Leaf.LeafType != TimestampedEntryLeafType {
  376. return nil, fmt.Errorf("Unsupported leaf type %s", entry.Leaf.LeafType)
  377. }
  378. switch entry.Leaf.TimestampedEntry.EntryType {
  379. case X509LogEntryType:
  380. return serializeV1CertSCTSignatureInput(sct.Timestamp, entry.Leaf.TimestampedEntry.X509Entry, entry.Leaf.TimestampedEntry.Extensions)
  381. case PrecertLogEntryType:
  382. return serializeV1PrecertSCTSignatureInput(sct.Timestamp, entry.Leaf.TimestampedEntry.PrecertEntry.IssuerKeyHash,
  383. entry.Leaf.TimestampedEntry.PrecertEntry.TBSCertificate,
  384. entry.Leaf.TimestampedEntry.Extensions)
  385. case XJSONLogEntryType:
  386. return serializeV1JSONSCTSignatureInput(sct.Timestamp, entry.Leaf.TimestampedEntry.JSONData)
  387. default:
  388. return nil, fmt.Errorf("unknown TimestampedEntryLeafType %s", entry.Leaf.TimestampedEntry.EntryType)
  389. }
  390. }
  391. // SerializeSCTSignatureInput serializes the passed in sct and log entry into
  392. // the correct format for signing.
  393. func SerializeSCTSignatureInput(sct SignedCertificateTimestamp, entry LogEntry) ([]byte, error) {
  394. switch sct.SCTVersion {
  395. case V1:
  396. return serializeV1SCTSignatureInput(sct, entry)
  397. default:
  398. return nil, fmt.Errorf("unknown SCT version %d", sct.SCTVersion)
  399. }
  400. }
  401. // SerializedLength will return the space (in bytes)
  402. func (sct SignedCertificateTimestamp) SerializedLength() (int, error) {
  403. switch sct.SCTVersion {
  404. case V1:
  405. extLen := len(sct.Extensions)
  406. sigLen := len(sct.Signature.Signature)
  407. return 1 + 32 + 8 + 2 + extLen + 2 + 2 + sigLen, nil
  408. default:
  409. return 0, ErrInvalidVersion
  410. }
  411. }
  412. func serializeV1SCTHere(sct SignedCertificateTimestamp, here []byte) ([]byte, error) {
  413. if sct.SCTVersion != V1 {
  414. return nil, ErrInvalidVersion
  415. }
  416. sctLen, err := sct.SerializedLength()
  417. if err != nil {
  418. return nil, err
  419. }
  420. if here == nil {
  421. here = make([]byte, sctLen)
  422. }
  423. if len(here) < sctLen {
  424. return nil, ErrNotEnoughBuffer
  425. }
  426. if err := checkExtensionsFormat(sct.Extensions); err != nil {
  427. return nil, err
  428. }
  429. here = here[0:sctLen]
  430. // Write Version
  431. here[0] = byte(sct.SCTVersion)
  432. // Write LogID
  433. copy(here[1:33], sct.LogID[:])
  434. // Write Timestamp
  435. binary.BigEndian.PutUint64(here[33:41], sct.Timestamp)
  436. // Write Extensions
  437. extLen := len(sct.Extensions)
  438. binary.BigEndian.PutUint16(here[41:43], uint16(extLen))
  439. n := 43 + extLen
  440. copy(here[43:n], sct.Extensions)
  441. // Write Signature
  442. _, err = marshalDigitallySignedHere(sct.Signature, here[n:])
  443. if err != nil {
  444. return nil, err
  445. }
  446. return here, nil
  447. }
  448. // SerializeSCTHere serializes the passed in sct into the format specified
  449. // by RFC6962 section 3.2.
  450. // If a bytes slice here is provided then it will attempt to serialize into the
  451. // provided byte slice, ErrNotEnoughBuffer will be returned if the buffer is
  452. // too small.
  453. // If a nil byte slice is provided, a buffer for will be allocated for you
  454. // The returned slice will be sliced to the correct length.
  455. func SerializeSCTHere(sct SignedCertificateTimestamp, here []byte) ([]byte, error) {
  456. switch sct.SCTVersion {
  457. case V1:
  458. return serializeV1SCTHere(sct, here)
  459. default:
  460. return nil, fmt.Errorf("unknown SCT version %d", sct.SCTVersion)
  461. }
  462. }
  463. // SerializeSCT serializes the passed in sct into the format specified
  464. // by RFC6962 section 3.2
  465. // Equivalent to SerializeSCTHere(sct, nil)
  466. func SerializeSCT(sct SignedCertificateTimestamp) ([]byte, error) {
  467. return SerializeSCTHere(sct, nil)
  468. }
  469. func deserializeSCTV1(r io.Reader, sct *SignedCertificateTimestamp) error {
  470. if err := binary.Read(r, binary.BigEndian, &sct.LogID); err != nil {
  471. return err
  472. }
  473. if err := binary.Read(r, binary.BigEndian, &sct.Timestamp); err != nil {
  474. return err
  475. }
  476. ext, err := readVarBytes(r, ExtensionsLengthBytes)
  477. if err != nil {
  478. return err
  479. }
  480. sct.Extensions = ext
  481. ds, err := UnmarshalDigitallySigned(r)
  482. if err != nil {
  483. return err
  484. }
  485. sct.Signature = *ds
  486. return nil
  487. }
  488. // DeserializeSCT reads an SCT from Reader.
  489. func DeserializeSCT(r io.Reader) (*SignedCertificateTimestamp, error) {
  490. var sct SignedCertificateTimestamp
  491. if err := binary.Read(r, binary.BigEndian, &sct.SCTVersion); err != nil {
  492. return nil, err
  493. }
  494. switch sct.SCTVersion {
  495. case V1:
  496. return &sct, deserializeSCTV1(r, &sct)
  497. default:
  498. return nil, fmt.Errorf("unknown SCT version %d", sct.SCTVersion)
  499. }
  500. }
  501. func serializeV1STHSignatureInput(sth SignedTreeHead) ([]byte, error) {
  502. if sth.Version != V1 {
  503. return nil, fmt.Errorf("invalid STH version %d", sth.Version)
  504. }
  505. if sth.TreeSize < 0 {
  506. return nil, fmt.Errorf("invalid tree size %d", sth.TreeSize)
  507. }
  508. if len(sth.SHA256RootHash) != crypto.SHA256.Size() {
  509. return nil, fmt.Errorf("invalid TreeHash length, got %d expected %d", len(sth.SHA256RootHash), crypto.SHA256.Size())
  510. }
  511. var buf bytes.Buffer
  512. if err := binary.Write(&buf, binary.BigEndian, V1); err != nil {
  513. return nil, err
  514. }
  515. if err := binary.Write(&buf, binary.BigEndian, TreeHashSignatureType); err != nil {
  516. return nil, err
  517. }
  518. if err := binary.Write(&buf, binary.BigEndian, sth.Timestamp); err != nil {
  519. return nil, err
  520. }
  521. if err := binary.Write(&buf, binary.BigEndian, sth.TreeSize); err != nil {
  522. return nil, err
  523. }
  524. if err := binary.Write(&buf, binary.BigEndian, sth.SHA256RootHash); err != nil {
  525. return nil, err
  526. }
  527. return buf.Bytes(), nil
  528. }
  529. // SerializeSTHSignatureInput serializes the passed in sth into the correct
  530. // format for signing.
  531. func SerializeSTHSignatureInput(sth SignedTreeHead) ([]byte, error) {
  532. switch sth.Version {
  533. case V1:
  534. return serializeV1STHSignatureInput(sth)
  535. default:
  536. return nil, fmt.Errorf("unsupported STH version %d", sth.Version)
  537. }
  538. }
  539. // SCTListSerializedLength determines the length of the required buffer should a SCT List need to be serialized
  540. func SCTListSerializedLength(scts []SignedCertificateTimestamp) (int, error) {
  541. if len(scts) == 0 {
  542. return 0, fmt.Errorf("SCT List empty")
  543. }
  544. sctListLen := 0
  545. for i, sct := range scts {
  546. n, err := sct.SerializedLength()
  547. if err != nil {
  548. return 0, fmt.Errorf("unable to determine length of SCT in position %d: %v", i, err)
  549. }
  550. if n > MaxSCTInListLength {
  551. return 0, fmt.Errorf("SCT in position %d too large: %d", i, n)
  552. }
  553. sctListLen += 2 + n
  554. }
  555. return sctListLen, nil
  556. }
  557. // SerializeSCTList serializes the passed-in slice of SignedCertificateTimestamp into a
  558. // byte slice as a SignedCertificateTimestampList (see RFC6962 Section 3.3)
  559. func SerializeSCTList(scts []SignedCertificateTimestamp) ([]byte, error) {
  560. size, err := SCTListSerializedLength(scts)
  561. if err != nil {
  562. return nil, err
  563. }
  564. fullSize := 2 + size // 2 bytes for length + size of SCT list
  565. if fullSize > MaxSCTListLength {
  566. return nil, fmt.Errorf("SCT List too large to serialize: %d", fullSize)
  567. }
  568. buf := new(bytes.Buffer)
  569. buf.Grow(fullSize)
  570. if err = writeUint(buf, uint64(size), 2); err != nil {
  571. return nil, err
  572. }
  573. for _, sct := range scts {
  574. serialized, err := SerializeSCT(sct)
  575. if err != nil {
  576. return nil, err
  577. }
  578. if err = writeVarBytes(buf, serialized, 2); err != nil {
  579. return nil, err
  580. }
  581. }
  582. return asn1.Marshal(buf.Bytes()) // transform to Octet String
  583. }
  584. // SerializeMerkleTreeLeaf writes MerkleTreeLeaf to Writer.
  585. // In case of error, w may contain garbage.
  586. func SerializeMerkleTreeLeaf(w io.Writer, m *MerkleTreeLeaf) error {
  587. if m.Version != V1 {
  588. return fmt.Errorf("unknown Version %d", m.Version)
  589. }
  590. if err := binary.Write(w, binary.BigEndian, m.Version); err != nil {
  591. return err
  592. }
  593. if m.LeafType != TimestampedEntryLeafType {
  594. return fmt.Errorf("unknown LeafType %d", m.LeafType)
  595. }
  596. if err := binary.Write(w, binary.BigEndian, m.LeafType); err != nil {
  597. return err
  598. }
  599. if err := SerializeTimestampedEntry(w, &m.TimestampedEntry); err != nil {
  600. return err
  601. }
  602. return nil
  603. }
  604. // CreateX509MerkleTreeLeaf generates a MerkleTreeLeaf for an X509 cert
  605. func CreateX509MerkleTreeLeaf(cert ASN1Cert, timestamp uint64) *MerkleTreeLeaf {
  606. return &MerkleTreeLeaf{
  607. Version: V1,
  608. LeafType: TimestampedEntryLeafType,
  609. TimestampedEntry: TimestampedEntry{
  610. Timestamp: timestamp,
  611. EntryType: X509LogEntryType,
  612. X509Entry: cert,
  613. },
  614. }
  615. }
  616. // CreateJSONMerkleTreeLeaf creates the merkle tree leaf for json data.
  617. func CreateJSONMerkleTreeLeaf(data interface{}, timestamp uint64) *MerkleTreeLeaf {
  618. jsonData, err := json.Marshal(AddJSONRequest{Data: data})
  619. if err != nil {
  620. return nil
  621. }
  622. // Match the JSON serialization implemented by json-c
  623. jsonStr := strings.Replace(string(jsonData), ":", ": ", -1)
  624. jsonStr = strings.Replace(jsonStr, ",", ", ", -1)
  625. jsonStr = strings.Replace(jsonStr, "{", "{ ", -1)
  626. jsonStr = strings.Replace(jsonStr, "}", " }", -1)
  627. jsonStr = strings.Replace(jsonStr, "/", `\/`, -1)
  628. // TODO: Pending google/certificate-transparency#1243, replace with
  629. // ObjectHash once supported by CT server.
  630. return &MerkleTreeLeaf{
  631. Version: V1,
  632. LeafType: TimestampedEntryLeafType,
  633. TimestampedEntry: TimestampedEntry{
  634. Timestamp: timestamp,
  635. EntryType: XJSONLogEntryType,
  636. JSONData: []byte(jsonStr),
  637. },
  638. }
  639. }