ct.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. package ct
  2. import (
  3. "context"
  4. "crypto/x509"
  5. "crypto/x509/pkix"
  6. "encoding/asn1"
  7. "encoding/pem"
  8. "io/ioutil"
  9. "log"
  10. "net/http"
  11. "time"
  12. ct "github.com/google/certificate-transparency-go"
  13. "github.com/google/certificate-transparency-go/client"
  14. "github.com/google/certificate-transparency-go/jsonclient"
  15. cttls "github.com/google/certificate-transparency-go/tls"
  16. ctx509 "github.com/google/certificate-transparency-go/x509"
  17. "github.com/pkg/errors"
  18. )
  19. var (
  20. oidExtensionCTPoison = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 3}
  21. oidSignedCertificateTimestampList = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11129, 2, 4, 2}
  22. )
  23. // Config represents the configuration for the certificate authority client.
  24. type Config struct {
  25. URI string `json:"uri"`
  26. Key string `json:"key"`
  27. NotAfterStart time.Time `json:"notAfterStart,omitempty"`
  28. NotAfterLimit time.Time `json:"notAfterLimit,omitempty"`
  29. }
  30. // Validate validates the ct configuration.
  31. func (c *Config) Validate() error {
  32. switch {
  33. case c.URI == "":
  34. return errors.New("ct uri cannot be empty")
  35. case c.Key == "":
  36. return errors.New("ct key cannot be empty")
  37. default:
  38. return nil
  39. }
  40. }
  41. // Client is the interface used to communicate with the certificate transparency logs.
  42. type Client interface {
  43. GetSCTs(asn1Data ...[]byte) (*SCT, error)
  44. SubmitToLogs(asn1Data ...[]byte) (*SCT, error)
  45. }
  46. type logClient interface {
  47. AddChain(ctx context.Context, chain []ct.ASN1Cert) (*ct.SignedCertificateTimestamp, error)
  48. AddPreChain(ctx context.Context, chain []ct.ASN1Cert) (*ct.SignedCertificateTimestamp, error)
  49. }
  50. // SCT represents a Signed Certificate Timestamp.
  51. type SCT struct {
  52. LogURL string
  53. SCT *ct.SignedCertificateTimestamp
  54. }
  55. // GetExtension returns the extension representing an SCT that will be added to
  56. // a certificate.
  57. func (t *SCT) GetExtension() pkix.Extension {
  58. val, err := cttls.Marshal(*t.SCT)
  59. if err != nil {
  60. panic(err)
  61. }
  62. value, err := cttls.Marshal(ctx509.SignedCertificateTimestampList{
  63. SCTList: []ctx509.SerializedSCT{
  64. {Val: val},
  65. },
  66. })
  67. if err != nil {
  68. panic(err)
  69. }
  70. rawValue, err := asn1.Marshal(value)
  71. if err != nil {
  72. panic(err)
  73. }
  74. return pkix.Extension{
  75. Id: oidSignedCertificateTimestampList,
  76. Critical: false,
  77. Value: rawValue,
  78. }
  79. }
  80. // AddPoisonExtension appends the ct poison extension to the given certificate.
  81. func AddPoisonExtension(cert *x509.Certificate) {
  82. cert.Extensions = append(cert.Extensions, pkix.Extension{
  83. Id: oidExtensionCTPoison,
  84. Critical: true,
  85. })
  86. }
  87. // ClientImpl is the implementation of a certificate transparency Client.
  88. type ClientImpl struct {
  89. config Config
  90. logClient logClient
  91. timeout time.Duration
  92. }
  93. // New creates a new Client
  94. func New(c Config) (*ClientImpl, error) {
  95. der, err := readPublicKey(c.Key)
  96. if err != nil {
  97. return nil, err
  98. }
  99. // Initialize ct client
  100. logClient, err := client.New(c.URI, &http.Client{}, jsonclient.Options{
  101. PublicKeyDER: der,
  102. UserAgent: "smallstep certificates",
  103. })
  104. if err != nil {
  105. return nil, errors.Wrapf(err, "failed to create client to %s", c.URI)
  106. }
  107. // Validate connection
  108. ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
  109. defer cancel()
  110. if _, err := logClient.GetSTH(ctx); err != nil {
  111. return nil, errors.Wrapf(err, "failed to connect to %s", c.URI)
  112. }
  113. log.Printf("connecting to CT log %s", c.URI)
  114. log.Println("CT support is experimental and can change at any time")
  115. return &ClientImpl{
  116. config: c,
  117. logClient: logClient,
  118. timeout: 30 * time.Second,
  119. }, nil
  120. }
  121. // GetSCTs submit the precertificate to the logs and returns the list of SCTs to
  122. // embed into the certificate.
  123. func (c *ClientImpl) GetSCTs(asn1Data ...[]byte) (*SCT, error) {
  124. chain := chainFromDERs(asn1Data)
  125. ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
  126. defer cancel()
  127. sct, err := c.logClient.AddPreChain(ctx, chain)
  128. if err != nil {
  129. return nil, errors.Wrapf(err, "failed to get SCT from %s", c.config.URI)
  130. }
  131. logLeafHash("AddPreChain", asn1Data, sct, true)
  132. return &SCT{
  133. LogURL: c.config.URI,
  134. SCT: sct,
  135. }, nil
  136. }
  137. // SubmitToLogs submits the certificate to the certificate transparency logs.
  138. func (c *ClientImpl) SubmitToLogs(asn1Data ...[]byte) (*SCT, error) {
  139. chain := chainFromDERs(asn1Data)
  140. ctx, cancel := context.WithTimeout(context.Background(), c.timeout)
  141. defer cancel()
  142. sct, err := c.logClient.AddChain(ctx, chain)
  143. if err != nil {
  144. return nil, errors.Wrapf(err, "failed submit certificate to %s", c.config.URI)
  145. }
  146. logLeafHash("AddChain", asn1Data, sct, false)
  147. return &SCT{
  148. LogURL: c.config.URI,
  149. SCT: sct,
  150. }, nil
  151. }
  152. // readPublicKey extracts the DER from the given file.
  153. func readPublicKey(filename string) ([]byte, error) {
  154. data, err := ioutil.ReadFile(filename)
  155. if err != nil {
  156. return nil, errors.Wrapf(err, "error reading %s", filename)
  157. }
  158. block, rest := pem.Decode(data)
  159. if block == nil || len(rest) > 0 {
  160. return nil, errors.Wrapf(err, "invalid public key %s", filename)
  161. }
  162. return block.Bytes, nil
  163. }
  164. func chainFromDERs(asn1Data [][]byte) []ct.ASN1Cert {
  165. var chain []ct.ASN1Cert
  166. for _, der := range asn1Data {
  167. chain = append(chain, ct.ASN1Cert{Data: der})
  168. }
  169. return chain
  170. }
  171. func logLeafHash(op string, asn1Data [][]byte, sct *ct.SignedCertificateTimestamp, isPrecert bool) {
  172. var etype ct.LogEntryType
  173. if isPrecert {
  174. etype = ct.PrecertLogEntryType
  175. } else {
  176. etype = ct.X509LogEntryType
  177. }
  178. chain := make([]*ctx509.Certificate, len(asn1Data))
  179. for i := range asn1Data {
  180. cert, err := ctx509.ParseCertificate(asn1Data[i])
  181. if err != nil {
  182. log.Println(err)
  183. return
  184. }
  185. chain[i] = cert
  186. }
  187. leafEntry, err := ct.MerkleTreeLeafFromChain(chain, etype, sct.Timestamp)
  188. if err != nil {
  189. log.Println(err)
  190. return
  191. }
  192. leafHash, err := ct.LeafHashForLeaf(leafEntry)
  193. if err != nil {
  194. log.Println(err)
  195. return
  196. }
  197. log.Printf("Op: %s, LogID: %x, LeafHash: %x, Timestamp: %d\n", op, sct.LogID.KeyID[:], leafHash, sct.Timestamp)
  198. }