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 2021 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 service is a fake S2A handshaker service.
package service
import (
"bytes"
"fmt"
"os"
"google.golang.org/grpc/codes"
commonpb "github.com/google/s2a-go/internal/proto/common_go_proto"
s2apb "github.com/google/s2a-go/internal/proto/s2a_go_proto"
)
type handshakeState int
const (
// initial is the state of the handshaker service before any handshake
// message has been received.
initial handshakeState = 0
// started is the state of the handshaker service when the handshake has
// been initiated but no bytes have been sent or received.
started handshakeState = 1
// sent is the state of the handshaker service when the handshake has been
// initiated and bytes have been sent.
sent handshakeState = 2
// completed is the state of the handshaker service when the handshake has
// been completed.
completed handshakeState = 3
)
const (
accessTokenEnvVariable = "S2A_ACCESS_TOKEN"
grpcAppProtocol = "grpc"
clientHelloFrame = "ClientHello"
clientFinishedFrame = "ClientFinished"
serverFrame = "ServerHelloAndFinished"
)
const (
inKey = "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
outKey = "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
)
// FakeHandshakerService implements the s2apb.S2AServiceServer. The fake
// handshaker service should not be used by more than 1 application at a time.
type FakeHandshakerService struct {
s2apb.S2AServiceServer
assistingClient bool
state handshakeState
peerIdentity *commonpb.Identity
localIdentity *commonpb.Identity
}
// SetUpSession sets up the S2A session.
func (hs *FakeHandshakerService) SetUpSession(stream s2apb.S2AService_SetUpSessionServer) error {
for {
sessionReq, err := stream.Recv()
if err != nil {
return fmt.Errorf("stream recv failed: %v", err)
}
if err := hs.authenticateRequest(sessionReq); err != nil {
return fmt.Errorf("S2A cannot authenticate the request: %v", err)
}
var resp *s2apb.SessionResp
receivedTicket := false
switch req := sessionReq.ReqOneof.(type) {
case *s2apb.SessionReq_ClientStart:
resp = hs.processClientStart(req)
case *s2apb.SessionReq_ServerStart:
resp = hs.processServerStart(req)
case *s2apb.SessionReq_Next:
resp = hs.processNext(req)
case *s2apb.SessionReq_ResumptionTicket:
resp = hs.processResumptionTicket(req)
receivedTicket = true
default:
return fmt.Errorf("session request has unexpected type %T", req)
}
if err = stream.Send(resp); err != nil {
return fmt.Errorf("stream send failed: %v", err)
}
if receivedTicket || resp.GetResult() != nil {
return nil
}
}
}
// processClientStart processes a ClientSessionStartReq.
func (hs *FakeHandshakerService) processClientStart(req *s2apb.SessionReq_ClientStart) *s2apb.SessionResp {
resp := s2apb.SessionResp{}
if hs.state != initial {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.FailedPrecondition),
Details: "client start handshake not in initial state",
}
return &resp
}
if len(req.ClientStart.GetApplicationProtocols()) != 1 ||
req.ClientStart.GetApplicationProtocols()[0] != grpcAppProtocol {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.InvalidArgument),
Details: "application protocol was not grpc",
}
return &resp
}
if req.ClientStart.GetMaxTlsVersion() != commonpb.TLSVersion_TLS1_3 {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.InvalidArgument),
Details: "max TLS version must be 1.3",
}
return &resp
}
if req.ClientStart.GetMinTlsVersion() != commonpb.TLSVersion_TLS1_3 {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.InvalidArgument),
Details: "min TLS version must be 1.3",
}
return &resp
}
resp.OutFrames = []byte(clientHelloFrame)
resp.BytesConsumed = 0
resp.Status = &s2apb.SessionStatus{Code: uint32(codes.OK)}
hs.localIdentity = req.ClientStart.LocalIdentity
if len(req.ClientStart.TargetIdentities) > 0 {
hs.peerIdentity = req.ClientStart.TargetIdentities[0]
}
hs.assistingClient = true
hs.state = sent
return &resp
}
// processServerStart processes a ServerSessionStartReq.
func (hs *FakeHandshakerService) processServerStart(req *s2apb.SessionReq_ServerStart) *s2apb.SessionResp {
resp := s2apb.SessionResp{}
if hs.state != initial {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.FailedPrecondition),
Details: "server start handshake not in initial state",
}
return &resp
}
if len(req.ServerStart.GetApplicationProtocols()) != 1 ||
req.ServerStart.GetApplicationProtocols()[0] != grpcAppProtocol {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.InvalidArgument),
Details: "application protocol was not grpc",
}
return &resp
}
if req.ServerStart.GetMaxTlsVersion() != commonpb.TLSVersion_TLS1_3 {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.InvalidArgument),
Details: "max TLS version must be 1.3",
}
return &resp
}
if req.ServerStart.GetMinTlsVersion() != commonpb.TLSVersion_TLS1_3 {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.InvalidArgument),
Details: "min TLS version must be 1.3",
}
return &resp
}
if len(req.ServerStart.InBytes) == 0 {
resp.BytesConsumed = 0
hs.state = started
} else if bytes.Equal(req.ServerStart.InBytes, []byte(clientHelloFrame)) {
resp.OutFrames = []byte(serverFrame)
resp.BytesConsumed = uint32(len(clientHelloFrame))
hs.state = sent
} else {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.Internal),
Details: "server start request did not have the correct input bytes",
}
return &resp
}
resp.Status = &s2apb.SessionStatus{Code: uint32(codes.OK)}
if len(req.ServerStart.LocalIdentities) > 0 {
hs.localIdentity = req.ServerStart.LocalIdentities[0]
}
hs.assistingClient = false
return &resp
}
// processNext processes a SessionNext request.
func (hs *FakeHandshakerService) processNext(req *s2apb.SessionReq_Next) *s2apb.SessionResp {
resp := s2apb.SessionResp{}
if hs.assistingClient {
if hs.state != sent {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.FailedPrecondition),
Details: "client handshake was not in sent state",
}
return &resp
}
if !bytes.Equal(req.Next.InBytes, []byte(serverFrame)) {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.Internal),
Details: "client request did not match server frame",
}
return &resp
}
resp.OutFrames = []byte(clientFinishedFrame)
resp.BytesConsumed = uint32(len(serverFrame))
hs.state = completed
} else {
if hs.state == started {
if !bytes.Equal(req.Next.InBytes, []byte(clientHelloFrame)) {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.Internal),
Details: "server request did not match client hello frame",
}
return &resp
}
resp.OutFrames = []byte(serverFrame)
resp.BytesConsumed = uint32(len(clientHelloFrame))
hs.state = sent
} else if hs.state == sent {
if !bytes.Equal(req.Next.InBytes[:len(clientFinishedFrame)], []byte(clientFinishedFrame)) {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.Internal),
Details: "server request did not match client finished frame",
}
return &resp
}
resp.BytesConsumed = uint32(len(clientFinishedFrame))
hs.state = completed
} else {
resp.Status = &s2apb.SessionStatus{
Code: uint32(codes.FailedPrecondition),
Details: "server request was not in expected state",
}
return &resp
}
}
resp.Status = &s2apb.SessionStatus{Code: uint32(codes.OK)}
if hs.state == completed {
resp.Result = hs.getSessionResult()
}
return &resp
}
// processResumptionTicket processes a ResumptionTicketReq request.
func (hs *FakeHandshakerService) processResumptionTicket(req *s2apb.SessionReq_ResumptionTicket) *s2apb.SessionResp {
return &s2apb.SessionResp{
Status: &s2apb.SessionStatus{Code: uint32(codes.OK)},
}
}
// getSessionResult returns a dummy SessionResult.
func (hs *FakeHandshakerService) getSessionResult() *s2apb.SessionResult {
res := s2apb.SessionResult{}
res.ApplicationProtocol = grpcAppProtocol
res.State = &s2apb.SessionState{
TlsVersion: commonpb.TLSVersion_TLS1_3,
TlsCiphersuite: commonpb.Ciphersuite_AES_128_GCM_SHA256,
InKey: []byte(inKey),
OutKey: []byte(outKey),
}
res.PeerIdentity = hs.peerIdentity
res.LocalIdentity = hs.localIdentity
return &res
}
func (hs *FakeHandshakerService) authenticateRequest(request *s2apb.SessionReq) error {
// If the S2A_ACCESS_TOKEN environment variable has not been set, then do not
// enforce anything on the request.
acceptedToken := os.Getenv(accessTokenEnvVariable)
if acceptedToken == "" {
return nil
}
if len(request.GetAuthMechanisms()) == 0 {
return fmt.Errorf("expected token but none was received")
}
for _, authMechanism := range request.GetAuthMechanisms() {
if authMechanism.GetToken() != acceptedToken {
return fmt.Errorf("received token: %s, expected token: %s", authMechanism.GetToken(), acceptedToken)
}
}
return nil
}
|