forked from google/certificate-transparency-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
proxy.go
210 lines (185 loc) · 6.44 KB
/
proxy.go
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
// Copyright 2019 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package submission contains code and structs for certificates submission proxy.
package submission
import (
"context"
"fmt"
"sync"
"time"
ct "github.com/RarimoVoting/certificate-transparency-go"
"github.com/RarimoVoting/certificate-transparency-go/asn1"
"github.com/RarimoVoting/certificate-transparency-go/ctpolicy"
"github.com/RarimoVoting/certificate-transparency-go/loglist3"
"github.com/RarimoVoting/certificate-transparency-go/schedule"
"github.com/RarimoVoting/certificate-transparency-go/tls"
"github.com/RarimoVoting/certificate-transparency-go/x509util"
"github.com/google/trillian/monitoring"
"k8s.io/klog/v2"
)
// CTPolicyType indicates CT-policy used for certificate submission.
type CTPolicyType int
// Policy type values:
const (
ChromeCTPolicy CTPolicyType = iota
AppleCTPolicy
)
var (
proxyOnce sync.Once
logListUpdates monitoring.Counter
rspLatency monitoring.Histogram // ep => value
)
// proxyInitMetrics initializes all the exported metrics.
func proxyInitMetrics(mf monitoring.MetricFactory) {
logListUpdates = mf.NewCounter("log_list_updates", "Number of Log-list updates")
rspLatency = mf.NewHistogram("http_latency", "Latency of policy-multiplexed add-responses in seconds", "ep")
}
// DistributorBuilder builds distributor instance for a given Log list.
type DistributorBuilder func(*loglist3.LogList) (*Distributor, error)
// GetDistributorBuilder given CT-policy type and Log-client builder produces
// Distributor c-tor.
func GetDistributorBuilder(plc CTPolicyType, lcBuilder LogClientBuilder, mf monitoring.MetricFactory) DistributorBuilder {
if plc == AppleCTPolicy {
return func(ll *loglist3.LogList) (*Distributor, error) {
return NewDistributor(ll, ctpolicy.AppleCTPolicy{}, lcBuilder, mf)
}
}
return func(ll *loglist3.LogList) (*Distributor, error) {
return NewDistributor(ll, ctpolicy.ChromeCTPolicy{}, lcBuilder, mf)
}
}
// ASN1MarshalSCTs serializes list of AssignedSCTs according to RFC6962 3.3
func ASN1MarshalSCTs(scts []*AssignedSCT) ([]byte, error) {
if len(scts) == 0 {
return nil, fmt.Errorf("ASN1MarshalSCTs requires positive number of SCTs, 0 provided")
}
unassignedSCTs := make([]*ct.SignedCertificateTimestamp, 0, len(scts))
for _, sct := range scts {
unassignedSCTs = append(unassignedSCTs, sct.SCT)
}
sctList, err := x509util.MarshalSCTsIntoSCTList(unassignedSCTs)
if err != nil {
return nil, err
}
encdSCTList, err := tls.Marshal(*sctList)
if err != nil {
return nil, err
}
encoded, err := asn1.Marshal(encdSCTList)
if err != nil {
return nil, err
}
return encoded, nil
}
// Proxy wraps Log List updates watcher and Distributor running on fresh Log List.
type Proxy struct {
Init chan bool
llRefreshInterval time.Duration
rootsRefreshInterval time.Duration
llWatcher *LogListManager
distributorBuilder DistributorBuilder
distMu sync.RWMutex // guards the distributor
dist *Distributor
distCancel context.CancelFunc // used to cancel distributor updates
}
// NewProxy creates an inactive Proxy instance. Call Run() to activate.
func NewProxy(llm *LogListManager, db DistributorBuilder, mf monitoring.MetricFactory) *Proxy {
var p Proxy
p.llWatcher = llm
p.distributorBuilder = db
p.Init = make(chan bool, 1)
p.rootsRefreshInterval = 24 * time.Hour
if mf == nil {
mf = monitoring.InertMetricFactory{}
}
proxyOnce.Do(func() { proxyInitMetrics(mf) })
return &p
}
// Run starts regular LogList checks and associated Distributor initialization.
// Sends true via Init channel when init is complete.
// Terminates upon context cancellation.
func (p *Proxy) Run(ctx context.Context, llRefresh time.Duration, rootsRefresh time.Duration) {
init := false
p.llRefreshInterval = llRefresh
p.rootsRefreshInterval = rootsRefresh
p.llWatcher.Run(ctx, llRefresh)
go func() {
for {
select {
case <-ctx.Done():
if !init {
close(p.Init)
}
return
case llData := <-p.llWatcher.LLUpdates:
logListUpdates.Inc()
if err := p.restartDistributor(ctx, llData.List); err != nil {
klog.Errorf("Unable to use Log-list:\n %v\n %v", err, llData.JSON)
} else if !init {
init = true
p.Init <- true
close(p.Init)
}
case err := <-p.llWatcher.Errors:
klog.Error(err)
}
}
}()
}
// restartDistributor activates new Distributor instance with Log List provided
// and sets it as active.
func (p *Proxy) restartDistributor(ctx context.Context, ll *loglist3.LogList) error {
d, err := p.distributorBuilder(ll)
if err != nil {
// losing ll info. No good.
return err
}
// Start refreshing roots periodically so they stay up-to-date.
refreshCtx, refreshCancel := context.WithCancel(ctx)
go schedule.Every(refreshCtx, p.rootsRefreshInterval, func(ectx context.Context) {
if errs := d.RefreshRoots(ectx); len(errs) > 0 {
for _, err := range errs {
klog.Warning(err)
}
}
})
p.distMu.Lock()
defer p.distMu.Unlock()
if p.distCancel != nil {
p.distCancel()
}
p.dist = d
p.distCancel = refreshCancel
return nil
}
// AddPreChain passes call to underlying Distributor instance.
func (p *Proxy) AddPreChain(ctx context.Context, rawChain [][]byte, loadPendingLogs bool) ([]*AssignedSCT, error) {
if p.dist == nil {
return []*AssignedSCT{}, fmt.Errorf("proxy distributor is not initialized. call Run()")
}
defer func(start time.Time) {
rspLatency.Observe(time.Since(start).Seconds(), "add-pre-chain")
}(time.Now())
return p.dist.AddPreChain(ctx, rawChain, loadPendingLogs)
}
// AddChain passes call to underlying Distributor instance.
func (p *Proxy) AddChain(ctx context.Context, rawChain [][]byte, loadPendingLogs bool) ([]*AssignedSCT, error) {
if p.dist == nil {
return []*AssignedSCT{}, fmt.Errorf("proxy distributor is not initialized. call Run()")
}
defer func(start time.Time) {
rspLatency.Observe(time.Since(start).Seconds(), "add-chain")
}(time.Now())
return p.dist.AddChain(ctx, rawChain, loadPendingLogs)
}