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 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
|
/*
*
* Copyright 2022 Google LLC
*
* 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
*
* https://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 fakes2av2 is a fake S2Av2 Go implementation.
package fakes2av2
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"log"
"time"
"google.golang.org/grpc/codes"
_ "embed"
commonpb "github.com/google/s2a-go/internal/proto/v2/common_go_proto"
s2av2ctx "github.com/google/s2a-go/internal/proto/v2/s2a_context_go_proto"
s2av2pb "github.com/google/s2a-go/internal/proto/v2/s2a_go_proto"
)
var (
//go:embed testdata/client_root_cert.pem
clientCert []byte
//go:embed testdata/client_root_cert.der
clientDERCert []byte
//go:embed testdata/client_root_key.pem
clientKey []byte
//go:embed testdata/server_root_cert.pem
serverCert []byte
//go:embed testdata/server_root_cert.der
serverDERCert []byte
//go:embed testdata/server_root_key.pem
serverKey []byte
)
// Server is a fake S2A Server for testing.
type Server struct {
s2av2pb.UnimplementedS2AServiceServer
// ExpectedToken is the token S2Av2 expects to be attached to the SessionReq.
ExpectedToken string
// ShouldNotReturnClientCredentials indicates whether the fake S2Av2 should
// not return credentials when GetTlsConfiguration is called by a client.
ShouldNotReturnClientCredentials bool
isAssistingClientSide bool
ServerAuthorizationPolicy []byte
// TODO(rmehta19): Decide whether to also store validationResult (bool).
// Set this after validating token attached to first SessionReq. Check
// this field before completing subsequent SessionReq.
}
// SetUpSession receives SessionReq, performs request, and returns a
// SessionResp, all on the server stream.
func (s *Server) SetUpSession(stream s2av2pb.S2AService_SetUpSessionServer) error {
for {
req, err := stream.Recv()
if err != nil {
log.Printf("Fake S2A Service: failed to receive SessionReq: %v", err)
return err
}
// Call one of the 4 possible RespOneof's
// TODO(rmehta19): Consider validating the body of the request.
var resp *s2av2pb.SessionResp
switch x := req.ReqOneof.(type) {
case *s2av2pb.SessionReq_GetTlsConfigurationReq:
if err := s.hasValidToken(req.GetAuthenticationMechanisms()); err != nil {
log.Printf("Fake S2A Service: authentication error: %v", err)
return err
}
if err := s.findConnectionSide(req); err != nil {
resp = &s2av2pb.SessionResp{
Status: &s2av2pb.Status{
Code: uint32(codes.InvalidArgument),
Details: err.Error(),
},
}
break
}
resp, err = getTLSConfiguration(req.GetGetTlsConfigurationReq(), s.ShouldNotReturnClientCredentials)
if err != nil {
log.Printf("Fake S2A Service: failed to build SessionResp with GetTlsConfigurationResp: %v", err)
return err
}
case *s2av2pb.SessionReq_OffloadPrivateKeyOperationReq:
resp, err = offloadPrivateKeyOperation(req.GetOffloadPrivateKeyOperationReq(), s.isAssistingClientSide)
if err != nil {
log.Printf("Fake S2A Service: failed to build SessionResp with OffloadPrivateKeyOperationResp: %v", err)
return err
}
case *s2av2pb.SessionReq_OffloadResumptionKeyOperationReq:
// TODO(rmehta19): Implement fake.
case *s2av2pb.SessionReq_ValidatePeerCertificateChainReq:
resp, err = validatePeerCertificateChain(req.GetValidatePeerCertificateChainReq(), s.ServerAuthorizationPolicy)
if err != nil {
log.Printf("Fake S2A Service: failed to build SessionResp with ValidatePeerCertificateChainResp: %v", err)
return err
}
default:
return fmt.Errorf("SessionReq.ReqOneof has unexpected type %T", x)
}
if err := stream.Send(resp); err != nil {
log.Printf("Fake S2A Service: failed to send SessionResp: %v", err)
return err
}
}
}
func (s *Server) findConnectionSide(req *s2av2pb.SessionReq) error {
switch connSide := req.GetGetTlsConfigurationReq().GetConnectionSide(); connSide {
case commonpb.ConnectionSide_CONNECTION_SIDE_CLIENT:
s.isAssistingClientSide = true
case commonpb.ConnectionSide_CONNECTION_SIDE_SERVER:
s.isAssistingClientSide = false
default:
return fmt.Errorf("unknown ConnectionSide: %v", connSide)
}
return nil
}
func (s *Server) hasValidToken(authMechanisms []*s2av2pb.AuthenticationMechanism) error {
if len(authMechanisms) == 0 {
return nil
}
for _, v := range authMechanisms {
token := v.GetToken()
if token == s.ExpectedToken {
return nil
}
}
return errors.New("SessionReq has no AuthenticationMechanism with a valid token")
}
func offloadPrivateKeyOperation(req *s2av2pb.OffloadPrivateKeyOperationReq, isAssistingClientSide bool) (*s2av2pb.SessionResp, error) {
switch x := req.GetOperation(); x {
case s2av2pb.OffloadPrivateKeyOperationReq_SIGN:
var root tls.Certificate
var err error
// Retrieve S2Av2 implementation of crypto.Signer.
if isAssistingClientSide {
root, err = tls.X509KeyPair(clientCert, clientKey)
if err != nil {
return nil, err
}
} else {
root, err = tls.X509KeyPair(serverCert, serverKey)
if err != nil {
return nil, err
}
}
var signedBytes []byte
if req.GetSignatureAlgorithm() == s2av2pb.SignatureAlgorithm_S2A_SSL_SIGN_RSA_PKCS1_SHA256 {
signedBytes, err = root.PrivateKey.(crypto.Signer).Sign(rand.Reader, req.GetSha256Digest(), crypto.SHA256)
if err != nil {
return nil, err
}
} else if req.GetSignatureAlgorithm() == s2av2pb.SignatureAlgorithm_S2A_SSL_SIGN_RSA_PSS_RSAE_SHA256 {
opts := &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash, Hash: crypto.SHA256}
signedBytes, err = root.PrivateKey.(crypto.Signer).Sign(rand.Reader, req.GetSha256Digest(), opts)
if err != nil {
return nil, err
}
} else {
return &s2av2pb.SessionResp{
Status: &s2av2pb.Status{
Code: uint32(codes.InvalidArgument),
Details: fmt.Sprintf("invalid signature algorithm: %v", req.GetSignatureAlgorithm()),
},
}, nil
}
return &s2av2pb.SessionResp{
Status: &s2av2pb.Status{
Code: uint32(codes.OK),
},
RespOneof: &s2av2pb.SessionResp_OffloadPrivateKeyOperationResp{
OffloadPrivateKeyOperationResp: &s2av2pb.OffloadPrivateKeyOperationResp{
OutBytes: signedBytes,
},
},
}, nil
case s2av2pb.OffloadPrivateKeyOperationReq_DECRYPT:
return nil, errors.New("decrypt operation not implemented yet")
default:
return nil, fmt.Errorf("unspecified private key operation requested: %d", x)
}
}
func validatePeerCertificateChain(req *s2av2pb.ValidatePeerCertificateChainReq, serverAuthorizationPolicy []byte) (*s2av2pb.SessionResp, error) {
switch x := req.PeerOneof.(type) {
case *s2av2pb.ValidatePeerCertificateChainReq_ClientPeer_:
return verifyClientPeer(req)
case *s2av2pb.ValidatePeerCertificateChainReq_ServerPeer_:
return verifyServerPeer(req, serverAuthorizationPolicy)
default:
err := fmt.Errorf("peer verification failed: invalid Peer type %T", x)
return buildValidatePeerCertificateChainSessionResp(uint32(codes.InvalidArgument), err.Error(), s2av2pb.ValidatePeerCertificateChainResp_FAILURE, err.Error(), &s2av2ctx.S2AContext{}), err
}
}
// TODO(rmehta19): Update this to return ciphersuites in Client/Server TlsConfiguration.
func getTLSConfiguration(req *s2av2pb.GetTlsConfigurationReq, shouldNotReturnClientCredentials bool) (*s2av2pb.SessionResp, error) {
if req.GetConnectionSide() == commonpb.ConnectionSide_CONNECTION_SIDE_CLIENT {
if shouldNotReturnClientCredentials {
return &s2av2pb.SessionResp{
Status: &s2av2pb.Status{
Code: uint32(codes.OK),
},
RespOneof: &s2av2pb.SessionResp_GetTlsConfigurationResp{
GetTlsConfigurationResp: &s2av2pb.GetTlsConfigurationResp{
TlsConfiguration: &s2av2pb.GetTlsConfigurationResp_ClientTlsConfiguration_{
ClientTlsConfiguration: &s2av2pb.GetTlsConfigurationResp_ClientTlsConfiguration{
MinTlsVersion: commonpb.TLSVersion_TLS_VERSION_1_3,
MaxTlsVersion: commonpb.TLSVersion_TLS_VERSION_1_3,
},
},
},
},
}, nil
}
return &s2av2pb.SessionResp{
Status: &s2av2pb.Status{
Code: uint32(codes.OK),
},
RespOneof: &s2av2pb.SessionResp_GetTlsConfigurationResp{
GetTlsConfigurationResp: &s2av2pb.GetTlsConfigurationResp{
TlsConfiguration: &s2av2pb.GetTlsConfigurationResp_ClientTlsConfiguration_{
ClientTlsConfiguration: &s2av2pb.GetTlsConfigurationResp_ClientTlsConfiguration{
CertificateChain: []string{
string(clientCert),
},
MinTlsVersion: commonpb.TLSVersion_TLS_VERSION_1_3,
MaxTlsVersion: commonpb.TLSVersion_TLS_VERSION_1_3,
},
},
},
},
}, nil
} else if req.GetConnectionSide() == commonpb.ConnectionSide_CONNECTION_SIDE_SERVER {
return &s2av2pb.SessionResp{
Status: &s2av2pb.Status{
Code: uint32(codes.OK),
},
RespOneof: &s2av2pb.SessionResp_GetTlsConfigurationResp{
GetTlsConfigurationResp: &s2av2pb.GetTlsConfigurationResp{
TlsConfiguration: &s2av2pb.GetTlsConfigurationResp_ServerTlsConfiguration_{
ServerTlsConfiguration: &s2av2pb.GetTlsConfigurationResp_ServerTlsConfiguration{
CertificateChain: []string{
string(serverCert),
},
MinTlsVersion: commonpb.TLSVersion_TLS_VERSION_1_3,
MaxTlsVersion: commonpb.TLSVersion_TLS_VERSION_1_3,
TlsResumptionEnabled: false,
RequestClientCertificate: s2av2pb.GetTlsConfigurationResp_ServerTlsConfiguration_REQUEST_AND_REQUIRE_CLIENT_CERTIFICATE_AND_VERIFY,
MaxOverheadOfTicketAead: 0,
},
},
},
},
}, nil
}
return nil, fmt.Errorf("unspecified connection side: %v", req.GetConnectionSide())
}
func buildValidatePeerCertificateChainSessionResp(StatusCode uint32, StatusDetails string, ValidationResult s2av2pb.ValidatePeerCertificateChainResp_ValidationResult, ValidationDetails string, Context *s2av2ctx.S2AContext) *s2av2pb.SessionResp {
return &s2av2pb.SessionResp{
Status: &s2av2pb.Status{
Code: StatusCode,
Details: StatusDetails,
},
RespOneof: &s2av2pb.SessionResp_ValidatePeerCertificateChainResp{
ValidatePeerCertificateChainResp: &s2av2pb.ValidatePeerCertificateChainResp{
ValidationResult: ValidationResult,
ValidationDetails: ValidationDetails,
Context: Context,
},
},
}
}
func verifyClientPeer(req *s2av2pb.ValidatePeerCertificateChainReq) (*s2av2pb.SessionResp, error) {
derCertChain := req.GetClientPeer().CertificateChain
if len(derCertChain) == 0 {
s := "client peer verification failed: client cert chain is empty"
return buildValidatePeerCertificateChainSessionResp(uint32(codes.OK), "", s2av2pb.ValidatePeerCertificateChainResp_FAILURE, s, &s2av2ctx.S2AContext{}), nil
}
// Obtain the set of root certificates.
rootCertPool := x509.NewCertPool()
if ok := rootCertPool.AppendCertsFromPEM(clientCert); ok != true {
err := errors.New("client peer verification failed: S2Av2 could not obtain/parse roots")
return buildValidatePeerCertificateChainSessionResp(uint32(codes.Internal), err.Error(), s2av2pb.ValidatePeerCertificateChainResp_FAILURE, err.Error(), &s2av2ctx.S2AContext{}), err
}
// Set the Intermediates: certs between leaf and root, excluding the leaf and root.
intermediateCertPool := x509.NewCertPool()
for i := 1; i < (len(derCertChain)); i++ {
x509Cert, err := x509.ParseCertificate(derCertChain[i])
if err != nil {
return buildValidatePeerCertificateChainSessionResp(uint32(codes.InvalidArgument), err.Error(), s2av2pb.ValidatePeerCertificateChainResp_FAILURE, err.Error(), &s2av2ctx.S2AContext{}), err
}
intermediateCertPool.AddCert(x509Cert)
}
// Verify the leaf certificate.
opts := x509.VerifyOptions{
CurrentTime: time.Now(),
Roots: rootCertPool,
Intermediates: intermediateCertPool,
}
x509LeafCert, err := x509.ParseCertificate(derCertChain[0])
if err != nil {
s := fmt.Sprintf("client peer verification failed: %v", err)
return buildValidatePeerCertificateChainSessionResp(uint32(codes.InvalidArgument), s, s2av2pb.ValidatePeerCertificateChainResp_FAILURE, s, &s2av2ctx.S2AContext{}), err
}
if _, err := x509LeafCert.Verify(opts); err != nil {
s := fmt.Sprintf("client peer verification failed: %v", err)
return buildValidatePeerCertificateChainSessionResp(uint32(codes.InvalidArgument), s, s2av2pb.ValidatePeerCertificateChainResp_FAILURE, s, &s2av2ctx.S2AContext{}), nil
}
return buildValidatePeerCertificateChainSessionResp(uint32(codes.OK), "", s2av2pb.ValidatePeerCertificateChainResp_SUCCESS, "client peer verification succeeded", &s2av2ctx.S2AContext{}), nil
}
func verifyServerPeer(req *s2av2pb.ValidatePeerCertificateChainReq, serverAuthorizationPolicy []byte) (*s2av2pb.SessionResp, error) {
if serverAuthorizationPolicy != nil {
if got := req.GetServerPeer().SerializedUnrestrictedClientPolicy; !bytes.Equal(got, serverAuthorizationPolicy) {
err := fmt.Errorf("server peer verification failed: invalid server authorization policy, expected: %s, got: %s",
serverAuthorizationPolicy, got)
return buildValidatePeerCertificateChainSessionResp(uint32(codes.Internal), err.Error(), s2av2pb.ValidatePeerCertificateChainResp_FAILURE, err.Error(), &s2av2ctx.S2AContext{}), err
}
}
derCertChain := req.GetServerPeer().CertificateChain
if len(derCertChain) == 0 {
s := "server peer verification failed: server cert chain is empty"
return buildValidatePeerCertificateChainSessionResp(uint32(codes.OK), "", s2av2pb.ValidatePeerCertificateChainResp_FAILURE, s, &s2av2ctx.S2AContext{}), nil
}
// Obtain the set of root certificates.
rootCertPool := x509.NewCertPool()
if ok := rootCertPool.AppendCertsFromPEM(serverCert); ok != true {
err := errors.New("server peer verification failed: S2Av2 could not obtain/parse roots")
return buildValidatePeerCertificateChainSessionResp(uint32(codes.Internal), err.Error(), s2av2pb.ValidatePeerCertificateChainResp_FAILURE, err.Error(), &s2av2ctx.S2AContext{}), err
}
// Set the Intermediates: certs between leaf and root, excluding the leaf and root.
intermediateCertPool := x509.NewCertPool()
for i := 1; i < (len(derCertChain)); i++ {
x509Cert, err := x509.ParseCertificate(derCertChain[i])
if err != nil {
return buildValidatePeerCertificateChainSessionResp(uint32(codes.InvalidArgument), err.Error(), s2av2pb.ValidatePeerCertificateChainResp_FAILURE, err.Error(), &s2av2ctx.S2AContext{}), err
}
intermediateCertPool.AddCert(x509Cert)
}
// Verify the leaf certificate.
opts := x509.VerifyOptions{
CurrentTime: time.Now(),
Roots: rootCertPool,
Intermediates: intermediateCertPool,
}
x509LeafCert, err := x509.ParseCertificate(derCertChain[0])
if err != nil {
s := fmt.Sprintf("server peer verification failed: %v", err)
return buildValidatePeerCertificateChainSessionResp(uint32(codes.InvalidArgument), s, s2av2pb.ValidatePeerCertificateChainResp_FAILURE, s, &s2av2ctx.S2AContext{}), err
}
if _, err := x509LeafCert.Verify(opts); err != nil {
s := fmt.Sprintf("server peer verification failed: %v", err)
return buildValidatePeerCertificateChainSessionResp(uint32(codes.InvalidArgument), s, s2av2pb.ValidatePeerCertificateChainResp_FAILURE, s, &s2av2ctx.S2AContext{}), nil
}
return buildValidatePeerCertificateChainSessionResp(uint32(codes.OK), "", s2av2pb.ValidatePeerCertificateChainResp_SUCCESS, "server peer verification succeeded", &s2av2ctx.S2AContext{}), nil
}
|