aboutsummaryrefslogtreecommitdiff
path: root/collect.go
blob: 53b7607e08303ce7c9cac5e93f96cc6bfdc7900e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package main

import (
	"container/heap"
	"context"
	"crypto/sha256"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"strings"
	"sync"
	"syscall"
	"time"

	"git.cs.kau.se/rasmoste/ct-sans/internal/chunk"
	"git.cs.kau.se/rasmoste/ct-sans/internal/merkle"
	"git.cs.kau.se/rasmoste/ct-sans/internal/utils"
	ct "github.com/google/certificate-transparency-go"
	"github.com/google/certificate-transparency-go/client"
	"github.com/google/certificate-transparency-go/jsonclient"
	"github.com/google/certificate-transparency-go/scanner"
	"gitlab.torproject.org/rgdd/ct/pkg/metadata"
)

func collect(opts options) error {
	b, err := os.ReadFile(fmt.Sprintf("%s/%s", opts.Directory, opts.metadataFile))
	if err != nil {
		return err
	}
	var md metadata.Metadata
	if err := json.Unmarshal(b, &md); err != nil {
		return err
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	var wg sync.WaitGroup
	defer wg.Wait()

	go func() {
		wg.Add(1)
		defer wg.Done()

		sigs := make(chan os.Signal, 1)
		defer close(sigs)

		// Sometimes some worker in scanner.Fetcher isn't shutdown
		// properly despite the parent context (including getRanges)
		// being done.  The below is an ugly hack to avoid hanging.
		wait := time.Second * 5 // TODO: set higher with real runs
		signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
		select {
		case <-sigs:
			fmt.Fprintf(os.Stderr, "INFO: received shutdown signal, please wait %v...\n", wait)
			cancel()
		case <-ctx.Done():
		}
		select {
		case <-time.After(wait):
			os.Exit(0)
		}
	}()

	for _, log := range utils.Logs(md) {
		go func(log metadata.Log) {
			wg.Add(1)
			defer wg.Done()

			chunks := make(chan *chunk.Chunk)
			defer close(chunks)

			id, _ := log.Key.ID()
			th, err := readState(opts, id[:])
			if err != nil {
				fmt.Fprintf(os.Stderr, "ERROR: %s: %v\n", *log.Description, err)
				cancel()
				return
			}
			sth, err := readSnapshot(opts, id[:])
			if err != nil {
				fmt.Fprintf(os.Stderr, "ERROR: %s: %v\n", *log.Description, err)
				cancel()
				return
			}
			cli, err := client.New(string(log.URL),
				&http.Client{Transport: &http.Transport{IdleConnTimeout: 120 * time.Second}},
				jsonclient.Options{UserAgent: opts.HTTPAgent},
			)
			if err != nil {
				fmt.Fprintf(os.Stderr, "ERROR: %s: %v\n", *log.Description, err)
				cancel()
				return
			}
			fetcher := scanner.NewFetcher(cli, &scanner.FetcherOptions{
				BatchSize:     int(opts.BatchSize),
				StartIndex:    th.TreeSize,
				EndIndex:      int64(sth.TreeSize),
				ParallelFetch: int(opts.WorkersPerLog),
			})

			//
			// Callback that puts downloaded certificates into a
			// chunk that a single sequencer can verify and persist
			//
			callback := func(eb scanner.EntryBatch) {
				leafHashes := [][sha256.Size]byte{}
				for i := 0; i < len(eb.Entries); i++ {
					leafHashes = append(leafHashes, merkle.HashLeafNode(eb.Entries[i].LeafInput))
				}
				sans, errs := utils.SANsFromLeafEntries(eb.Start, eb.Entries)
				for _, err := range errs {
					fmt.Fprintf(os.Stderr, "WARNING: %s: %v", *log.Description, err)
				}
				chunks <- &chunk.Chunk{eb.Start, leafHashes, sans}
			}

			//
			// Sequencer that waits for sufficiently large chunks
			// before verifying inclusion proofs and persisting an
			// intermediate tree head (size and root hash) as well
			// as the SANs that were observed up until that point.
			//
			go func() {
				wg.Add(1)
				defer wg.Done()
				defer fmt.Fprintf(os.Stderr, "INFO: %s: shutdown sequencer\n", *log.Description)

				h := &chunk.ChunkHeap{}
				heap.Init(h)
				curr := th.TreeSize
				for {
					select {
					case <-ctx.Done():
						if h.Sequence(curr) {
							c := h.TPop()
							if _, err := persistChunk(cli, opts, id[:], 0, c); err != nil {
								fmt.Fprintf(os.Stderr, "ERROR: %s: %v\n", err)
							}
						}
						return
					case c, ok := <-chunks:
						if ok {
							h.TPush(c)
						}
						if !h.Sequence(curr) {
							continue
						}

						c = h.TPop()
						putBack, err := persistChunk(cli, opts, id[:], int64(opts.PersistSize), c)
						if err != nil {
							cancel()
							fmt.Fprintf(os.Stderr, "ERROR: %s: %v\n", *log.Description, err)
							return
						}
						if putBack {
							h.TPush(c)
							continue
						}

						curr += int64(len(c.LeafHashes))
					}
				}
			}()

			if err := fetcher.Run(ctx, callback); err != nil {
				fmt.Fprintf(os.Stderr, "ERROR: %s: %v\n", *log.Description, err)
				cancel()
				return
			}

			fmt.Fprintf(os.Stderr, "INFO: %s: fetch completed\n", *log.Description)
			for len(chunks) > 0 {
				select {
				case <-ctx.Done():
					return
				case <-time.After(1 * time.Second):
					fmt.Fprintf(os.Stderr, "DEBUG: %s: waiting for chunks to be consumed\n", *log.Description)
				}
			}
		}(log)
		break
	}

	time.Sleep(1 * time.Second)
	return fmt.Errorf("TODO")
}

type treeHead struct {
	TreeSize int64             `json:"tree_size"`
	RootHash [sha256.Size]byte `json:root_hash"`
}

func readState(opts options, logID []byte) (treeHead, error) {
	if _, err := os.Stat(fmt.Sprintf("%s/%x/%s", opts.logDirectory, logID, opts.stateFile)); err != nil {
		return treeHead{0, sha256.Sum256(nil)}, nil
	}
	b, err := os.ReadFile(fmt.Sprintf("%s/%x/%s", opts.logDirectory, logID, opts.stateFile))
	if err != nil {
		return treeHead{}, err
	}
	var th treeHead
	if err := json.Unmarshal(b, &th); err != nil {
		return treeHead{}, err
	}
	return th, nil
}

func readSnapshot(opts options, logID []byte) (ct.SignedTreeHead, error) {
	b, err := os.ReadFile(fmt.Sprintf("%s/%x/%s", opts.logDirectory, logID, opts.sthFile))
	if err != nil {
		return ct.SignedTreeHead{}, err
	}
	var sth ct.SignedTreeHead
	if err := json.Unmarshal(b, &sth); err != nil {
		return ct.SignedTreeHead{}, err
	}
	return sth, nil
}

func persistChunk(cli *client.LogClient, opts options, logID []byte, minSequence int64, c *chunk.Chunk) (bool, error) {
	chunkSize := int64(len(c.LeafHashes))
	if chunkSize == 0 {
		return false, nil // nothing to persist
	}
	if chunkSize < minSequence {
		return true, nil // wait for more leaves
	}

	// Read persisted tree state from disk
	oldTH, err := readState(opts, logID)
	if err != nil {
		return false, err
	}
	if oldTH.TreeSize != c.Start {
		return false, fmt.Errorf("disk state says next index is %d, in-memory says %d", oldTH.TreeSize, c.Start)
	}
	// Read signed tree head from disk
	sth, err := readSnapshot(opts, logID)
	if err != nil {
		return false, err
	}
	// Derive next intermediate tree state from a compact range
	//
	// Santity checks: expected indces/sizes and consistent root hashes.
	// This is redundant, but could, e.g., catch bugs with our storage.
	//
	// Independent context because we need to run inclusion and consistency
	// queries after the parent context is cancelled to persist on shutdown
	//
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	newTH := treeHead{TreeSize: c.Start + chunkSize}
	p, err := cli.GetProofByHash(ctx, c.LeafHashes[0][:], uint64(newTH.TreeSize))
	if err != nil {
		fmt.Fprintf(os.Stderr, "WARNING: %x: %v\n", logID, err)
		return true, nil // try again later
	}
	if p.LeafIndex != c.Start {
		return false, fmt.Errorf("log says proof for entry %d is at index %d", c.Start, p.LeafIndex)
	}
	if newTH.RootHash, err = merkle.TreeHeadFromRangeProof(c.LeafHashes, uint64(c.Start), utils.Proof(p.AuditPath)); err != nil {
		return false, err
	}
	hashes, err := cli.GetSTHConsistency(ctx, uint64(oldTH.TreeSize), uint64(newTH.TreeSize))
	if err != nil {
		return true, nil // try again later
	}
	if err := merkle.VerifyConsistency(uint64(oldTH.TreeSize), uint64(newTH.TreeSize), oldTH.RootHash, newTH.RootHash, utils.Proof(hashes)); err != nil {
		return false, fmt.Errorf("%d %x is inconsistent with on-disk state: %v", newTH.TreeSize, newTH.RootHash, err)
	}

	// Check that new tree state is consistent with the signed tree head
	if hashes, err = cli.GetSTHConsistency(ctx, uint64(newTH.TreeSize), sth.TreeSize); err != nil {
		return true, nil // try again later
	}
	if err := merkle.VerifyConsistency(uint64(newTH.TreeSize), sth.TreeSize, newTH.RootHash, sth.SHA256RootHash, utils.Proof(hashes)); err != nil {
		return false, fmt.Errorf("%d %x is inconsistent with signed tree head: %v", newTH.TreeSize, newTH.RootHash, err)
	}

	// Persist SANs to disk
	fp, err := os.OpenFile(fmt.Sprintf("%s/%x/%s", opts.logDirectory, logID, opts.sansFile), os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		return false, err
	}
	defer fp.Close()
	if _, err := fp.WriteString(strings.Join(c.SANs, "\n") + "\n"); err != nil {
		return false, err
	}
	if err := fp.Sync(); err != nil {
		return false, err
	}

	// Persist new tree state to disk
	b, err := json.Marshal(&newTH)
	if err != nil {
		return false, err
	}
	if err := os.WriteFile(fmt.Sprintf("%s/%x/%s", opts.logDirectory, logID, opts.stateFile), b, 0644); err != nil {
		return false, err
	}

	fmt.Fprintf(os.Stderr, "DEBUG: %x: persist: start=%d next=%d\n", logID, oldTH.TreeSize, newTH.TreeSize)
	return false, nil
}