-
Notifications
You must be signed in to change notification settings - Fork 128
/
grpc_server.go
306 lines (272 loc) · 10.4 KB
/
grpc_server.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
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
// Copyright 2022 The Sigstore Authors.
//
// 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 server
import (
"context"
"crypto"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"strings"
"github.com/coreos/go-oidc/v3/oidc"
ctclient "github.com/google/certificate-transparency-go/client"
certauth "github.com/sigstore/fulcio/pkg/ca"
"github.com/sigstore/fulcio/pkg/challenges"
"github.com/sigstore/fulcio/pkg/config"
"github.com/sigstore/fulcio/pkg/ctl"
fulciogrpc "github.com/sigstore/fulcio/pkg/generated/protobuf"
"github.com/sigstore/fulcio/pkg/log"
"github.com/sigstore/sigstore/pkg/cryptoutils"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
)
type grpcCAServer struct {
fulciogrpc.UnimplementedCAServer
ct *ctclient.LogClient
ca certauth.CertificateAuthority
}
func NewGRPCCAServer(ct *ctclient.LogClient, ca certauth.CertificateAuthority) fulciogrpc.CAServer {
return &grpcCAServer{
ct: ct,
ca: ca,
}
}
const (
MetadataOIDCTokenKey = "oidcidentitytoken"
)
func (g *grpcCAServer) CreateSigningCertificate(ctx context.Context, request *fulciogrpc.CreateSigningCertificateRequest) (*fulciogrpc.SigningCertificate, error) {
logger := log.ContextLogger(ctx)
// OIDC token either is passed in gRPC field or was extracted from HTTP headers
token := ""
if request.Credentials != nil {
token = request.Credentials.GetOidcIdentityToken()
}
if token == "" {
if md, ok := metadata.FromIncomingContext(ctx); ok {
vals := md.Get(MetadataOIDCTokenKey)
if len(vals) == 1 {
token = vals[0]
}
}
}
// Authenticate OIDC ID token by checking signature
idtoken, err := authorize(ctx, token)
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.Unauthenticated, err, invalidCredentials)
}
// Parse authenticated ID token into principal
// TODO:(nsmith5) replace this and authorize call above with
// just identity.IssuerPool.Authenticate()
principal, err := challenges.PrincipalFromIDToken(ctx, idtoken)
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.InvalidArgument, err, invalidIdentityToken)
}
var publicKey crypto.PublicKey
// Verify caller is in possession of their private key and extract
// public key from request.
if len(request.GetCertificateSigningRequest()) > 0 {
// Option 1: Verify CSR
csr, err := cryptoutils.ParseCSR(request.GetCertificateSigningRequest())
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.InvalidArgument, err, invalidCSR)
}
// Parse public key and check for weak key parameters
publicKey = csr.PublicKey
if err := cryptoutils.ValidatePubKey(publicKey); err != nil {
return nil, handleFulcioGRPCError(ctx, codes.InvalidArgument, err, insecurePublicKey)
}
if err := csr.CheckSignature(); err != nil {
return nil, handleFulcioGRPCError(ctx, codes.InvalidArgument, err, invalidSignature)
}
} else {
// Option 2: Check the signature for proof of possession of a private key
var (
pubKeyContent string
proofOfPossession []byte
err error
)
if request.GetPublicKeyRequest() != nil {
if request.GetPublicKeyRequest().PublicKey != nil {
pubKeyContent = request.GetPublicKeyRequest().PublicKey.Content
}
proofOfPossession = request.GetPublicKeyRequest().ProofOfPossession
}
// Parse public key and check for weak parameters
publicKey, err = challenges.ParsePublicKey(pubKeyContent)
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.InvalidArgument, err, invalidPublicKey)
}
if err := cryptoutils.ValidatePubKey(publicKey); err != nil {
return nil, handleFulcioGRPCError(ctx, codes.InvalidArgument, err, insecurePublicKey)
}
// Check proof of possession signature
if err := challenges.CheckSignature(publicKey, proofOfPossession, principal.Name(ctx)); err != nil {
return nil, handleFulcioGRPCError(ctx, codes.InvalidArgument, err, invalidSignature)
}
}
var csc *certauth.CodeSigningCertificate
var sctBytes []byte
result := &fulciogrpc.SigningCertificate{}
// For CAs that do not support embedded SCTs or if the CT log is not configured
if sctCa, ok := g.ca.(certauth.EmbeddedSCTCA); !ok || g.ct == nil {
// currently configured CA doesn't support pre-certificate flow required to embed SCT in final certificate
csc, err = g.ca.CreateCertificate(ctx, principal, publicKey)
if err != nil {
// if the error was due to invalid input in the request, return HTTP 400
if _, ok := err.(certauth.ValidationError); ok {
return nil, handleFulcioGRPCError(ctx, codes.InvalidArgument, err, err.Error())
}
err = fmt.Errorf("Error creating certificate: %w", err)
// otherwise return a 500 error to reflect that it is a transient server issue that the client can't resolve
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, genericCAError)
}
// Submit to CTL
if g.ct != nil {
sct, err := g.ct.AddChain(ctx, ctl.BuildCTChain(csc.FinalCertificate, csc.FinalChain))
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, failedToEnterCertInCTL)
}
// convert to AddChainResponse because Cosign expects this struct.
addChainResp, err := ctl.ToAddChainResponse(sct)
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, failedToMarshalSCT)
}
sctBytes, err = json.Marshal(addChainResp)
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, failedToMarshalSCT)
}
} else {
logger.Info("Skipping CT log upload.")
}
finalPEM, err := csc.CertPEM()
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, failedToMarshalCert)
}
finalChainPEM, err := csc.ChainPEM()
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, failedToMarshalCert)
}
result.Certificate = &fulciogrpc.SigningCertificate_SignedCertificateDetachedSct{
SignedCertificateDetachedSct: &fulciogrpc.SigningCertificateDetachedSCT{
Chain: &fulciogrpc.CertificateChain{
Certificates: append([]string{finalPEM}, finalChainPEM...),
},
},
}
if len(sctBytes) > 0 {
result.GetSignedCertificateDetachedSct().SignedCertificateTimestamp = sctBytes
}
} else {
precert, err := sctCa.CreatePrecertificate(ctx, principal, publicKey)
if err != nil {
// if the error was due to invalid input in the request, return HTTP 400
if _, ok := err.(certauth.ValidationError); ok {
return nil, handleFulcioGRPCError(ctx, codes.InvalidArgument, err, err.Error())
}
err = fmt.Errorf("Error creating a pre-certificate and chain: %w", err)
// otherwise return a 500 error to reflect that it is a transient server issue that the client can't resolve
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, genericCAError)
}
// submit precertificate and chain to CT log
sct, err := g.ct.AddPreChain(ctx, ctl.BuildCTChain(precert.PreCert, precert.CertChain))
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, failedToEnterCertInCTL)
}
csc, err = sctCa.IssueFinalCertificate(ctx, precert, sct)
if err != nil {
err = fmt.Errorf("Error issuing final certificate using the pre-certificate with CA backend: %w", err)
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, genericCAError)
}
finalPEM, err := csc.CertPEM()
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, failedToMarshalCert)
}
finalChainPEM, err := csc.ChainPEM()
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, failedToMarshalCert)
}
result.Certificate = &fulciogrpc.SigningCertificate_SignedCertificateEmbeddedSct{
SignedCertificateEmbeddedSct: &fulciogrpc.SigningCertificateEmbeddedSCT{
Chain: &fulciogrpc.CertificateChain{
Certificates: append([]string{finalPEM}, finalChainPEM...),
},
},
}
}
metricNewEntries.Inc()
return result, nil
}
func (g *grpcCAServer) GetTrustBundle(ctx context.Context, _ *fulciogrpc.GetTrustBundleRequest) (*fulciogrpc.TrustBundle, error) {
trustBundle, err := g.ca.TrustBundle(ctx)
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, retrieveTrustBundleCAError)
}
resp := &fulciogrpc.TrustBundle{
Chains: []*fulciogrpc.CertificateChain{},
}
for _, chain := range trustBundle {
certChain := &fulciogrpc.CertificateChain{}
for _, cert := range chain {
certPEM, err := cryptoutils.MarshalCertificateToPEM(cert)
if err != nil {
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, marshalingCertificateChainBundleCAError)
}
certChain.Certificates = append(certChain.Certificates, string(certPEM))
}
resp.Chains = append(resp.Chains, certChain)
}
return resp, nil
}
func (g *grpcCAServer) GetConfiguration(ctx context.Context, _ *fulciogrpc.GetConfigurationRequest) (*fulciogrpc.Configuration, error) {
cfg := config.FromContext(ctx)
if cfg == nil {
err := errors.New("configuration not loaded")
return nil, handleFulcioGRPCError(ctx, codes.Internal, err, loadingFulcioConfigurationError)
}
return &fulciogrpc.Configuration{
Issuers: cfg.ToIssuers(),
}, nil
}
func extractIssuer(token string) (string, error) {
parts := strings.Split(token, ".")
if len(parts) != 3 {
return "", fmt.Errorf("oidc: malformed jwt, expected 3 parts got %d", len(parts))
}
raw, err := base64.RawURLEncoding.DecodeString(parts[1])
if err != nil {
return "", fmt.Errorf("oidc: malformed jwt payload: %w", err)
}
var payload struct {
Issuer string `json:"iss"`
}
if err := json.Unmarshal(raw, &payload); err != nil {
return "", fmt.Errorf("oidc: failed to unmarshal claims: %w", err)
}
return payload.Issuer, nil
}
// We do this to bypass needing actual OIDC tokens for unit testing.
var authorize = actualAuthorize
func actualAuthorize(ctx context.Context, token string) (*oidc.IDToken, error) {
issuer, err := extractIssuer(token)
if err != nil {
return nil, err
}
verifier, ok := config.FromContext(ctx).GetVerifier(issuer)
if !ok {
return nil, fmt.Errorf("unsupported issuer: %s", issuer)
}
return verifier.Verify(ctx, token)
}