serialization.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. // Copyright 2015 Google LLC. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package ct
  15. import (
  16. "crypto"
  17. "crypto/sha256"
  18. "fmt"
  19. "time"
  20. "github.com/google/certificate-transparency-go/tls"
  21. "github.com/google/certificate-transparency-go/x509"
  22. )
  23. // SerializeSCTSignatureInput serializes the passed in sct and log entry into
  24. // the correct format for signing.
  25. func SerializeSCTSignatureInput(sct SignedCertificateTimestamp, entry LogEntry) ([]byte, error) {
  26. switch sct.SCTVersion {
  27. case V1:
  28. input := CertificateTimestamp{
  29. SCTVersion: sct.SCTVersion,
  30. SignatureType: CertificateTimestampSignatureType,
  31. Timestamp: sct.Timestamp,
  32. EntryType: entry.Leaf.TimestampedEntry.EntryType,
  33. Extensions: sct.Extensions,
  34. }
  35. switch entry.Leaf.TimestampedEntry.EntryType {
  36. case X509LogEntryType:
  37. input.X509Entry = entry.Leaf.TimestampedEntry.X509Entry
  38. case PrecertLogEntryType:
  39. input.PrecertEntry = &PreCert{
  40. IssuerKeyHash: entry.Leaf.TimestampedEntry.PrecertEntry.IssuerKeyHash,
  41. TBSCertificate: entry.Leaf.TimestampedEntry.PrecertEntry.TBSCertificate,
  42. }
  43. default:
  44. return nil, fmt.Errorf("unsupported entry type %s", entry.Leaf.TimestampedEntry.EntryType)
  45. }
  46. return tls.Marshal(input)
  47. default:
  48. return nil, fmt.Errorf("unknown SCT version %d", sct.SCTVersion)
  49. }
  50. }
  51. // SerializeSTHSignatureInput serializes the passed in STH into the correct
  52. // format for signing.
  53. func SerializeSTHSignatureInput(sth SignedTreeHead) ([]byte, error) {
  54. switch sth.Version {
  55. case V1:
  56. if len(sth.SHA256RootHash) != crypto.SHA256.Size() {
  57. return nil, fmt.Errorf("invalid TreeHash length, got %d expected %d", len(sth.SHA256RootHash), crypto.SHA256.Size())
  58. }
  59. input := TreeHeadSignature{
  60. Version: sth.Version,
  61. SignatureType: TreeHashSignatureType,
  62. Timestamp: sth.Timestamp,
  63. TreeSize: sth.TreeSize,
  64. SHA256RootHash: sth.SHA256RootHash,
  65. }
  66. return tls.Marshal(input)
  67. default:
  68. return nil, fmt.Errorf("unsupported STH version %d", sth.Version)
  69. }
  70. }
  71. // CreateX509MerkleTreeLeaf generates a MerkleTreeLeaf for an X509 cert
  72. func CreateX509MerkleTreeLeaf(cert ASN1Cert, timestamp uint64) *MerkleTreeLeaf {
  73. return &MerkleTreeLeaf{
  74. Version: V1,
  75. LeafType: TimestampedEntryLeafType,
  76. TimestampedEntry: &TimestampedEntry{
  77. Timestamp: timestamp,
  78. EntryType: X509LogEntryType,
  79. X509Entry: &cert,
  80. },
  81. }
  82. }
  83. // MerkleTreeLeafFromRawChain generates a MerkleTreeLeaf from a chain (in DER-encoded form) and timestamp.
  84. func MerkleTreeLeafFromRawChain(rawChain []ASN1Cert, etype LogEntryType, timestamp uint64) (*MerkleTreeLeaf, error) {
  85. // Need at most 3 of the chain
  86. count := 3
  87. if count > len(rawChain) {
  88. count = len(rawChain)
  89. }
  90. chain := make([]*x509.Certificate, count)
  91. for i := range chain {
  92. cert, err := x509.ParseCertificate(rawChain[i].Data)
  93. if x509.IsFatal(err) {
  94. return nil, fmt.Errorf("failed to parse chain[%d] cert: %v", i, err)
  95. }
  96. chain[i] = cert
  97. }
  98. return MerkleTreeLeafFromChain(chain, etype, timestamp)
  99. }
  100. // MerkleTreeLeafFromChain generates a MerkleTreeLeaf from a chain and timestamp.
  101. func MerkleTreeLeafFromChain(chain []*x509.Certificate, etype LogEntryType, timestamp uint64) (*MerkleTreeLeaf, error) {
  102. leaf := MerkleTreeLeaf{
  103. Version: V1,
  104. LeafType: TimestampedEntryLeafType,
  105. TimestampedEntry: &TimestampedEntry{
  106. EntryType: etype,
  107. Timestamp: timestamp,
  108. },
  109. }
  110. if etype == X509LogEntryType {
  111. leaf.TimestampedEntry.X509Entry = &ASN1Cert{Data: chain[0].Raw}
  112. return &leaf, nil
  113. }
  114. if etype != PrecertLogEntryType {
  115. return nil, fmt.Errorf("unknown LogEntryType %d", etype)
  116. }
  117. // Pre-certs are more complicated. First, parse the leaf pre-cert and its
  118. // putative issuer.
  119. if len(chain) < 2 {
  120. return nil, fmt.Errorf("no issuer cert available for precert leaf building")
  121. }
  122. issuer := chain[1]
  123. cert := chain[0]
  124. var preIssuer *x509.Certificate
  125. if IsPreIssuer(issuer) {
  126. // Replace the cert's issuance information with details from the pre-issuer.
  127. preIssuer = issuer
  128. // The issuer of the pre-cert is not going to be the issuer of the final
  129. // cert. Change to use the final issuer's key hash.
  130. if len(chain) < 3 {
  131. return nil, fmt.Errorf("no issuer cert available for pre-issuer")
  132. }
  133. issuer = chain[2]
  134. }
  135. // Next, post-process the DER-encoded TBSCertificate, to remove the CT poison
  136. // extension and possibly update the issuer field.
  137. defangedTBS, err := x509.BuildPrecertTBS(cert.RawTBSCertificate, preIssuer)
  138. if err != nil {
  139. return nil, fmt.Errorf("failed to remove poison extension: %v", err)
  140. }
  141. leaf.TimestampedEntry.EntryType = PrecertLogEntryType
  142. leaf.TimestampedEntry.PrecertEntry = &PreCert{
  143. IssuerKeyHash: sha256.Sum256(issuer.RawSubjectPublicKeyInfo),
  144. TBSCertificate: defangedTBS,
  145. }
  146. return &leaf, nil
  147. }
  148. // MerkleTreeLeafForEmbeddedSCT generates a MerkleTreeLeaf from a chain and an
  149. // SCT timestamp, where the leaf certificate at chain[0] is a certificate that
  150. // contains embedded SCTs. It is assumed that the timestamp provided is from
  151. // one of the SCTs embedded within the leaf certificate.
  152. func MerkleTreeLeafForEmbeddedSCT(chain []*x509.Certificate, timestamp uint64) (*MerkleTreeLeaf, error) {
  153. // For building the leaf for a certificate and SCT where the SCT is embedded
  154. // in the certificate, we need to build the original precertificate TBS
  155. // data. First, parse the leaf cert and its issuer.
  156. if len(chain) < 2 {
  157. return nil, fmt.Errorf("no issuer cert available for precert leaf building")
  158. }
  159. issuer := chain[1]
  160. cert := chain[0]
  161. // Next, post-process the DER-encoded TBSCertificate, to remove the SCTList
  162. // extension.
  163. tbs, err := x509.RemoveSCTList(cert.RawTBSCertificate)
  164. if err != nil {
  165. return nil, fmt.Errorf("failed to remove SCT List extension: %v", err)
  166. }
  167. return &MerkleTreeLeaf{
  168. Version: V1,
  169. LeafType: TimestampedEntryLeafType,
  170. TimestampedEntry: &TimestampedEntry{
  171. EntryType: PrecertLogEntryType,
  172. Timestamp: timestamp,
  173. PrecertEntry: &PreCert{
  174. IssuerKeyHash: sha256.Sum256(issuer.RawSubjectPublicKeyInfo),
  175. TBSCertificate: tbs,
  176. },
  177. },
  178. }, nil
  179. }
  180. // LeafHashForLeaf returns the leaf hash for a Merkle tree leaf.
  181. func LeafHashForLeaf(leaf *MerkleTreeLeaf) ([sha256.Size]byte, error) {
  182. leafData, err := tls.Marshal(*leaf)
  183. if err != nil {
  184. return [sha256.Size]byte{}, fmt.Errorf("failed to tls-encode MerkleTreeLeaf: %s", err)
  185. }
  186. data := append([]byte{TreeLeafPrefix}, leafData...)
  187. leafHash := sha256.Sum256(data)
  188. return leafHash, nil
  189. }
  190. // IsPreIssuer indicates whether a certificate is a pre-cert issuer with the specific
  191. // certificate transparency extended key usage.
  192. func IsPreIssuer(issuer *x509.Certificate) bool {
  193. for _, eku := range issuer.ExtKeyUsage {
  194. if eku == x509.ExtKeyUsageCertificateTransparency {
  195. return true
  196. }
  197. }
  198. return false
  199. }
  200. // RawLogEntryFromLeaf converts a LeafEntry object (which has the raw leaf data
  201. // after JSON parsing) into a RawLogEntry object (i.e. a TLS-parsed structure).
  202. func RawLogEntryFromLeaf(index int64, entry *LeafEntry) (*RawLogEntry, error) {
  203. ret := RawLogEntry{Index: index}
  204. if rest, err := tls.Unmarshal(entry.LeafInput, &ret.Leaf); err != nil {
  205. return nil, fmt.Errorf("failed to unmarshal MerkleTreeLeaf: %v", err)
  206. } else if len(rest) > 0 {
  207. return nil, fmt.Errorf("MerkleTreeLeaf: trailing data %d bytes", len(rest))
  208. }
  209. switch eType := ret.Leaf.TimestampedEntry.EntryType; eType {
  210. case X509LogEntryType:
  211. var certChain CertificateChain
  212. if rest, err := tls.Unmarshal(entry.ExtraData, &certChain); err != nil {
  213. return nil, fmt.Errorf("failed to unmarshal CertificateChain: %v", err)
  214. } else if len(rest) > 0 {
  215. return nil, fmt.Errorf("CertificateChain: trailing data %d bytes", len(rest))
  216. }
  217. ret.Cert = *ret.Leaf.TimestampedEntry.X509Entry
  218. ret.Chain = certChain.Entries
  219. case PrecertLogEntryType:
  220. var precertChain PrecertChainEntry
  221. if rest, err := tls.Unmarshal(entry.ExtraData, &precertChain); err != nil {
  222. return nil, fmt.Errorf("failed to unmarshal PrecertChainEntry: %v", err)
  223. } else if len(rest) > 0 {
  224. return nil, fmt.Errorf("PrecertChainEntry: trailing data %d bytes", len(rest))
  225. }
  226. ret.Cert = precertChain.PreCertificate
  227. ret.Chain = precertChain.CertificateChain
  228. default:
  229. // TODO(pavelkalinnikov): Section 4.6 of RFC6962 implies that unknown types
  230. // are not errors. We should revisit how we process this case.
  231. return nil, fmt.Errorf("unknown entry type: %v", eType)
  232. }
  233. return &ret, nil
  234. }
  235. // ToLogEntry converts RawLogEntry to a LogEntry, which includes an x509-parsed
  236. // (pre-)certificate.
  237. //
  238. // Note that this function may return a valid LogEntry object and a non-nil
  239. // error value, when the error indicates a non-fatal parsing error.
  240. func (rle *RawLogEntry) ToLogEntry() (*LogEntry, error) {
  241. var err error
  242. entry := LogEntry{Index: rle.Index, Leaf: rle.Leaf, Chain: rle.Chain}
  243. switch eType := rle.Leaf.TimestampedEntry.EntryType; eType {
  244. case X509LogEntryType:
  245. entry.X509Cert, err = rle.Leaf.X509Certificate()
  246. if x509.IsFatal(err) {
  247. return nil, fmt.Errorf("failed to parse certificate: %v", err)
  248. }
  249. case PrecertLogEntryType:
  250. var tbsCert *x509.Certificate
  251. tbsCert, err = rle.Leaf.Precertificate()
  252. if x509.IsFatal(err) {
  253. return nil, fmt.Errorf("failed to parse precertificate: %v", err)
  254. }
  255. entry.Precert = &Precertificate{
  256. Submitted: rle.Cert,
  257. IssuerKeyHash: rle.Leaf.TimestampedEntry.PrecertEntry.IssuerKeyHash,
  258. TBSCertificate: tbsCert,
  259. }
  260. default:
  261. return nil, fmt.Errorf("unknown entry type: %v", eType)
  262. }
  263. // err may be non-nil for a non-fatal error.
  264. return &entry, err
  265. }
  266. // LogEntryFromLeaf converts a LeafEntry object (which has the raw leaf data
  267. // after JSON parsing) into a LogEntry object (which includes x509.Certificate
  268. // objects, after TLS and ASN.1 parsing).
  269. //
  270. // Note that this function may return a valid LogEntry object and a non-nil
  271. // error value, when the error indicates a non-fatal parsing error.
  272. func LogEntryFromLeaf(index int64, leaf *LeafEntry) (*LogEntry, error) {
  273. rle, err := RawLogEntryFromLeaf(index, leaf)
  274. if err != nil {
  275. return nil, err
  276. }
  277. return rle.ToLogEntry()
  278. }
  279. // TimestampToTime converts a timestamp in the style of RFC 6962 (milliseconds
  280. // since UNIX epoch) to a Go Time.
  281. func TimestampToTime(ts uint64) time.Time {
  282. secs := int64(ts / 1000)
  283. msecs := int64(ts % 1000)
  284. return time.Unix(secs, msecs*1000000)
  285. }