-
Notifications
You must be signed in to change notification settings - Fork 153
/
signer_gen.go
196 lines (183 loc) · 5.64 KB
/
signer_gen.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
// Copyright 2020 Anapaya Systems
//
// 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 trust
import (
"context"
"crypto"
"crypto/x509"
"time"
"github.com/scionproto/scion/pkg/addr"
"github.com/scionproto/scion/pkg/private/serrors"
"github.com/scionproto/scion/pkg/scrypto/cppki"
"github.com/scionproto/scion/pkg/scrypto/signed"
"github.com/scionproto/scion/private/trust/internal/metrics"
)
// KeyRing provides private keys.
type KeyRing interface {
PrivateKeys(ctx context.Context) ([]crypto.Signer, error)
}
// SignerGen generates signers from the keys available in key dir.
type SignerGen struct {
IA addr.IA
KeyRing KeyRing
DB DB // FIXME(roosd): Eventually this should use a crypto provider
// ExtKeyUsage filters the available certificates for specific key usage types.
// If ExtKeyUsage is not ExtKeyUsageAny, Generate will return a Signer with
// a certificate supporting this usage type (if one exists).
ExtKeyUsage x509.ExtKeyUsage
}
// Generate fetches private keys from the key ring and searches active
// certificate chains that authenticate the corresponding public key. The
// returned signer uses the private key which is backed by the certificate chain
// with the highest expiration time.
func (s SignerGen) Generate(ctx context.Context) ([]Signer, error) {
l := metrics.SignerLabels{}
keys, err := s.KeyRing.PrivateKeys(ctx)
if err != nil {
metrics.Signer.Generate(l.WithResult(metrics.ErrKey)).Inc()
return nil, err
}
if len(keys) == 0 {
metrics.Signer.Generate(l.WithResult(metrics.ErrKey)).Inc()
return nil, serrors.New("no private key found")
}
trcs, res, err := activeTRCs(ctx, s.DB, s.IA.ISD())
if err != nil {
metrics.Signer.Generate(l.WithResult(res)).Inc()
return nil, serrors.WrapStr("loading TRC", err)
}
var bests []Signer
for _, key := range keys {
signer, err := s.bestForKey(ctx, key, trcs)
if err != nil {
metrics.Signer.Generate(l.WithResult(metrics.ErrDB)).Inc()
return nil, err
}
if signer == nil {
continue
}
bests = append(bests, *signer)
}
if len(bests) == 0 {
metrics.Signer.Generate(l.WithResult(metrics.ErrNotFound)).Inc()
return nil, serrors.New("no certificate found", "num_private_keys", len(keys))
}
metrics.Signer.Generate(l.WithResult(metrics.Success)).Inc()
return bests, nil
}
func (s *SignerGen) bestForKey(
ctx context.Context,
key crypto.Signer,
trcs []cppki.SignedTRC,
) (*Signer, error) {
// FIXME(roosd): We currently take the sha1 sum of the public key.
// The final implementation needs to be smarter than that, but this
// requires a proper design that also considers certificate renewal.
skid, err := cppki.SubjectKeyID(key.Public())
if err != nil {
// Do not return an error. We might still find a key with a matching
// certificate later on.
return nil, nil
}
algo, err := signed.SelectSignatureAlgorithm(key.Public())
if err != nil {
return nil, err
}
now := time.Now()
chains, err := s.DB.Chains(ctx, ChainQuery{
IA: s.IA,
SubjectKeyID: skid,
Validity: cppki.Validity{
NotBefore: now,
NotAfter: now,
},
})
if err != nil {
// TODO metrics.Signer.Generate(l.WithResult(metrics.ErrDB)).Inc()
return nil, err
}
if s.ExtKeyUsage != x509.ExtKeyUsageAny {
chains = filterChains(chains, s.ExtKeyUsage)
}
chain := bestChain(&trcs[0].TRC, chains)
if chain == nil && len(trcs) == 1 {
return nil, nil
}
var inGrace bool
// Attempt to find a chain that is verifiable only in grace period. If we
// have not found a chain yet.
if chain == nil && len(trcs) == 2 {
chain = bestChain(&trcs[1].TRC, chains)
if chain == nil {
return nil, nil
}
inGrace = true
}
expiry := min(chain[0].NotAfter, trcs[0].TRC.Validity.NotAfter)
if inGrace {
// In the grace period the expiry is the minimum of the chain expiry,
// the grace period defined in the new TRC, and the expiry of the
// previous TRC.
expiry = min(
min(chain[0].NotAfter, trcs[0].TRC.GracePeriodEnd()),
trcs[1].TRC.Validity.NotAfter,
)
}
return &Signer{
PrivateKey: key,
Algorithm: algo,
IA: s.IA,
TRCID: trcs[0].TRC.ID,
Subject: chain[0].Subject,
Chain: chain,
SubjectKeyID: chain[0].SubjectKeyId,
Expiration: expiry,
ChainValidity: cppki.Validity{
NotBefore: chain[0].NotBefore,
NotAfter: chain[0].NotAfter,
},
InGrace: inGrace,
}, nil
}
// filterChains returns only the chains with matching key usage.
func filterChains(chains [][]*x509.Certificate, keyUsage x509.ExtKeyUsage) [][]*x509.Certificate {
filtered := make([][]*x509.Certificate, 0, len(chains))
for _, chain := range chains {
if err := verifyExtendedKeyUsage(chain[0], keyUsage); err != nil {
continue
}
filtered = append(filtered, chain)
}
return filtered
}
func bestChain(trc *cppki.TRC, chains [][]*x509.Certificate) []*x509.Certificate {
opts := cppki.VerifyOptions{TRC: []*cppki.TRC{trc}}
var best []*x509.Certificate
for _, chain := range chains {
if err := cppki.VerifyChain(chain, opts); err != nil {
continue
}
if len(best) > 0 && chain[0].NotAfter.Before(best[0].NotAfter) {
continue
}
best = chain
}
return best
}
func min(a, b time.Time) time.Time {
if a.Before(b) {
return a
}
return b
}