Debian Codegraph @

internal/certificatetransparency/ct-tiled.go

raw symbols SCIP
1 package certificatetransparency
2
3 import (
4 "bufio"
5 "context"
6 "fmt"
7 "io"
8 "net/http"
9 "strconv"
10 "strings"
11
12 ct "github.com/google/certificate-transparency-go"
13 "golang.org/x/crypto/cryptobyte"
14 )
15
16 const TileSize = 256
17
18 // TiledCheckpoint represents the checkpoint information from a tiled CT log
19 type TiledCheckpoint struct {
20 Origin string
21 Size uint64
22 Hash string
23 }
24
25 // TileLeaf represents a single entry in a tile
26 type TileLeaf struct {
27 Timestamp uint64
28 EntryType uint16
29 X509Entry []byte // For X.509 certificates
30 PrecertEntry []byte // For precertificates
31 Chain [][]byte
32 IssuerKeyHash [32]byte
33 }
34
35 // EncodeTilePath encodes a tile index into the proper path format
36 func EncodeTilePath(index uint64) string {
37 if index == 0 {
38 return "000"
39 }
40
41 // Collect 3-digit groups
42 var groups []uint64
43 for n := index; n > 0; n /= 1000 {
44 groups = append(groups, n%1000)
45 }
46
47 // Build path from groups in reverse
48 var b strings.Builder
49 for i := len(groups) - 1; i >= 0; i-- {
50 if i < len(groups)-1 {
51 b.WriteByte('/')
52 }
53 if i > 0 {
54 b.WriteByte('x')
55 }
56 fmt.Fprintf(&b, "%03d", groups[i])
57 }
58
59 return b.String()
60 }
61
62 // FetchCheckpoint fetches the checkpoint from a tiled CT log using the provided client
63 func FetchCheckpoint(ctx context.Context, client *http.Client, baseURL string) (*TiledCheckpoint, error) {
64 baseURL = strings.TrimRight(baseURL, "/")
65 url := fmt.Sprintf("%s/checkpoint", baseURL)
66 req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
67 if err != nil {
68 return nil, fmt.Errorf("creating request: %w", err)
69 }
70 req.Header.Set("User-Agent", userAgent)
71
72 resp, err := client.Do(req)
73 if err != nil {
74 return nil, fmt.Errorf("fetching checkpoint: %w", err)
75 }
76 defer resp.Body.Close()
77
78 if resp.StatusCode != http.StatusOK {
79 return nil, fmt.Errorf("checkpoint request failed with status: %d", resp.StatusCode)
80 }
81
82 scanner := bufio.NewScanner(resp.Body)
83 lines := make([]string, 0, 3)
84 for scanner.Scan() {
85 lines = append(lines, scanner.Text())
86 }
87
88 if err := scanner.Err(); err != nil {
89 return nil, fmt.Errorf("reading checkpoint response: %w", err)
90 }
91
92 if len(lines) < 3 {
93 return nil, fmt.Errorf("invalid checkpoint format: expected at least 3 lines, got %d", len(lines))
94 }
95
96 size, err := strconv.ParseUint(lines[1], 10, 64)
97 if err != nil {
98 return nil, fmt.Errorf("parsing tree size: %w", err)
99 }
100
101 return &TiledCheckpoint{
102 Origin: lines[0],
103 Size: size,
104 Hash: lines[2],
105 }, nil
106 }
107
108 // FetchTile fetches a tile from the tiled CT log using the provided client.
109 // If partialWidth > 0, fetches a partial tile with that width (1-255).
110 func FetchTile(ctx context.Context, client *http.Client, baseURL string, tileIndex uint64, partialWidth uint64) ([]TileLeaf, error) {
111 baseURL = strings.TrimRight(baseURL, "/")
112 tilePath := EncodeTilePath(tileIndex)
113 if partialWidth > 0 {
114 tilePath = fmt.Sprintf("%s.p/%d", tilePath, partialWidth)
115 }
116 url := fmt.Sprintf("%s/tile/data/%s", baseURL, tilePath)
117
118 req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
119 if err != nil {
120 return nil, fmt.Errorf("creating request: %w", err)
121 }
122 req.Header.Set("User-Agent", userAgent)
123
124 resp, err := client.Do(req)
125 if err != nil {
126 return nil, fmt.Errorf("fetching tile %d: %w", tileIndex, err)
127 }
128 defer resp.Body.Close()
129
130 if resp.StatusCode != http.StatusOK {
131 return nil, fmt.Errorf("tile request failed with status: %d", resp.StatusCode)
132 }
133
134 data, err := io.ReadAll(resp.Body)
135 if err != nil {
136 return nil, fmt.Errorf("reading tile data: %w", err)
137 }
138
139 return ParseTileData(data)
140 }
141
142 // ParseTileData parses the binary tile data into TileLeaf entries using cryptobyte
143 func ParseTileData(data []byte) ([]TileLeaf, error) {
144 var leaves []TileLeaf
145 s := cryptobyte.String(data)
146
147 for !s.Empty() {
148 var leaf TileLeaf
149
150 if !s.ReadUint64(&leaf.Timestamp) || !s.ReadUint16(&leaf.EntryType) {
151 return nil, fmt.Errorf("invalid data tile header")
152 }
153
154 switch leaf.EntryType {
155 case 0: // x509_entry
156 var cert cryptobyte.String
157 var extensions, fingerprints cryptobyte.String
158 if !s.ReadUint24LengthPrefixed(&cert) ||
159 !s.ReadUint16LengthPrefixed(&extensions) ||
160 !s.ReadUint16LengthPrefixed(&fingerprints) {
161 return nil, fmt.Errorf("invalid data tile x509_entry")
162 }
163 leaf.X509Entry = append([]byte(nil), cert...)
164 for !fingerprints.Empty() {
165 var fp [32]byte
166 if !fingerprints.CopyBytes(fp[:]) {
167 return nil, fmt.Errorf("invalid fingerprints: truncated")
168 }
169 leaf.Chain = append(leaf.Chain, fp[:])
170 }
171
172 case 1: // precert_entry
173 var issuerKeyHash [32]byte
174 var defangedCrt, extensions, entry, fingerprints cryptobyte.String
175 if !s.CopyBytes(issuerKeyHash[:]) ||
176 !s.ReadUint24LengthPrefixed(&defangedCrt) ||
177 !s.ReadUint16LengthPrefixed(&extensions) ||
178 !s.ReadUint24LengthPrefixed(&entry) ||
179 !s.ReadUint16LengthPrefixed(&fingerprints) {
180 return nil, fmt.Errorf("invalid data tile precert_entry")
181 }
182 leaf.PrecertEntry = append([]byte(nil), defangedCrt...)
183 leaf.IssuerKeyHash = issuerKeyHash
184 for !fingerprints.Empty() {
185 var fp [32]byte
186 if !fingerprints.CopyBytes(fp[:]) {
187 return nil, fmt.Errorf("invalid fingerprints: truncated")
188 }
189 leaf.Chain = append(leaf.Chain, fp[:])
190 }
191
192 default:
193 return nil, fmt.Errorf("unknown entry type: %d", leaf.EntryType)
194 }
195
196 leaves = append(leaves, leaf)
197 }
198 return leaves, nil
199 }
200
201 // ConvertTileLeafToRawLogEntry converts a TileLeaf to ct.RawLogEntry for compatibility
202 func ConvertTileLeafToRawLogEntry(leaf TileLeaf, index uint64) *ct.RawLogEntry {
203 rawEntry := &ct.RawLogEntry{
204 Index: int64(index),
205 Leaf: ct.MerkleTreeLeaf{
206 Version: ct.V1,
207 LeafType: ct.TimestampedEntryLeafType,
208 },
209 }
210
211 switch leaf.EntryType {
212 case 0: // x509_entry
213 // Use the DER certificate from X509Entry
214 certData := leaf.X509Entry
215 rawEntry.Leaf.TimestampedEntry = &ct.TimestampedEntry{
216 Timestamp: leaf.Timestamp,
217 EntryType: ct.X509LogEntryType,
218 X509Entry: &ct.ASN1Cert{Data: certData},
219 }
220 rawEntry.Cert = ct.ASN1Cert{Data: certData}
221
222 case 1: // precert_entry
223 // Build a minimal PreCert. TBSCertificate is the defanged TBS; IssuerKeyHash from tile.
224 rawEntry.Leaf.TimestampedEntry = &ct.TimestampedEntry{
225 Timestamp: leaf.Timestamp,
226 EntryType: ct.PrecertLogEntryType,
227 PrecertEntry: &ct.PreCert{
228 IssuerKeyHash: leaf.IssuerKeyHash,
229 TBSCertificate: leaf.PrecertEntry,
230 },
231 }
232
233 default:
234 // Unknown type; leave as zero-value
235 }
236
237 return rawEntry
238 }