From d4709a2b9e6d2ae7d8b36996b395818941565a09 Mon Sep 17 00:00:00 2001 From: Yuxuan Li Date: Thu, 13 Dec 2018 10:50:00 -0800 Subject: [PATCH 1/2] example: encryption --- .../features/encryption/ALTS/client/main.go | 63 ++++++++++++++ .../features/encryption/ALTS/server/main.go | 59 +++++++++++++ examples/features/encryption/README.md | 85 +++++++++++++++++++ .../features/encryption/TLS/client/main.go | 67 +++++++++++++++ .../features/encryption/TLS/server/main.go | 64 ++++++++++++++ 5 files changed, 338 insertions(+) create mode 100644 examples/features/encryption/ALTS/client/main.go create mode 100644 examples/features/encryption/ALTS/server/main.go create mode 100644 examples/features/encryption/README.md create mode 100644 examples/features/encryption/TLS/client/main.go create mode 100644 examples/features/encryption/TLS/server/main.go diff --git a/examples/features/encryption/ALTS/client/main.go b/examples/features/encryption/ALTS/client/main.go new file mode 100644 index 000000000000..50bde879cc4c --- /dev/null +++ b/examples/features/encryption/ALTS/client/main.go @@ -0,0 +1,63 @@ +/* + * + * Copyright 2018 gRPC 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 main + +import ( + "context" + "fmt" + "log" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/alts" + pb "google.golang.org/grpc/examples/helloworld/helloworld" +) + +const ( + address = "localhost:50051" +) + +// callSayHello calls SayHello on c with the given name, and prints the +// response. +func callSayHello(c pb.GreeterClient, name string) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name}) + if err != nil { + log.Fatalf("client.SayHello(_) = _, %v", err) + } + fmt.Println("Greeting: ", r.Message) +} + +func main() { + // Create alts based credential. + altsTC := alts.NewClientCreds(alts.DefaultClientOptions()) + + // Set up a connection to the server. + conn, err := grpc.Dial(address, grpc.WithTransportCredentials(altsTC)) + if err != nil { + log.Fatalf("did not connect: %v", err) + } + defer conn.Close() + + fmt.Println("--- calling helloworld.Greeter/SayHello ---") + // Make a greeter client and send an RPC. + hwc := pb.NewGreeterClient(conn) + callSayHello(hwc, "world") +} diff --git a/examples/features/encryption/ALTS/server/main.go b/examples/features/encryption/ALTS/server/main.go new file mode 100644 index 000000000000..4fc3dbf24b09 --- /dev/null +++ b/examples/features/encryption/ALTS/server/main.go @@ -0,0 +1,59 @@ +/* + * + * Copyright 2018 gRPC 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 main + +import ( + "context" + "log" + "net" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/alts" + pb "google.golang.org/grpc/examples/helloworld/helloworld" +) + +const ( + port = ":50051" +) + +// hwServer is used to implement helloworld.GreeterServer. +type hwServer struct{} + +// SayHello implements helloworld.GreeterServer +func (s *hwServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { + return &pb.HelloReply{Message: "Hello " + in.Name}, nil +} + +func main() { + lis, err := net.Listen("tcp", port) + if err != nil { + log.Fatalf("failed to listen: %v", err) + } + // Create alts based credential. + altsTC := alts.NewServerCreds(alts.DefaultServerOptions()) + + s := grpc.NewServer(grpc.Creds(altsTC)) + + // Register Greeter on the server. + pb.RegisterGreeterServer(s, &hwServer{}) + + if err := s.Serve(lis); err != nil { + log.Fatalf("failed to serve: %v", err) + } +} diff --git a/examples/features/encryption/README.md b/examples/features/encryption/README.md new file mode 100644 index 000000000000..6c454b38f8fd --- /dev/null +++ b/examples/features/encryption/README.md @@ -0,0 +1,85 @@ +# Encryption + +The example for encryption includes two individual examples for TLS and ALTS +encryption mechanism respectively. + +## Try it + +In each example's subdirectory: + +``` +go run server/main.go +``` + +``` +go run client/main.go +``` + +## Explanation + +### TLS + +TLS is a commonly used cryptographic protocol to provide end-to-end +communication security. In the example, we show how to set up a server +authenticated TLS connection to transmit RPC. + +In our `grpc/credentials` package, we provide several convenience methods to +create grpc +[`credentials.TransportCredentials`](https://godoc.org/google.golang.org/grpc/credentials#TransportCredentials) +base on TLS. Refer to the +[godoc](https://godoc.org/google.golang.org/grpc/credentials) for details. + +In our example, we use the public/private keys created ahead: +* "server1.pem" contains the server certificate (public key). +* "server1.key" contains the server private key. +* "ca.pem" contains the certificate (certificate authority) +that can verify the server's certificate. + +On server side, we provide the paths to "server1.pem" and "server1.key" to +configure TLS and create the server credential using +[`credentials.NewServerTLSFromFile`](https://godoc.org/google.golang.org/grpc/credentials#NewServerTLSFromFile). + +On client side, we provide the path to the "ca.pem" to configure TLS and create +the client credential using +[`credentials.NewClientTLSFromFile`](https://godoc.org/google.golang.org/grpc/credentials#NewClientTLSFromFile). +Note that we override the server name with "x.test.youtube.com", as the server +certificate is valid for *.test.youtube.com but not localhost. It is solely for +the convenience of making an example. + +Once the credentials have been created at both sides, we can start the server +with the just created server credential (by calling +[`grpc.Creds`](https://godoc.org/google.golang.org/grpc#Creds)) and let client dial +to the server with the created client credential (by calling +[`grpc.WithTransportCredentials`](https://godoc.org/google.golang.org/grpc#WithTransportCredentials)) + +And finally we make an RPC call over the created `grpc.ClientConn` to test the secure +connection based upon TLS is successfully up. + +### ALTS + +ALTS is the Google's Application Layer Transport Security, which supports mutual +authentication and transport encryption. Note that ALTS is currently only +supported on Google Cloud Platform, and therefore you can only run the example +successfully in a GCP environment. In our example, we show how to initiate a +secure connection that is based on ALTS. + +Unlike TLS, ALTS makes certificate/key management transparent to user. So it is +easier to set up. + +On server side, first call +[`alts.DefaultServerOptions`](https://godoc.org/google.golang.org/grpc/credentials/alts#DefaultServerOptions) +to get the configuration for alts and then provide the configuration to +[`alts.NewServerCreds`](https://godoc.org/google.golang.org/grpc/credentials/alts#NewServerCreds) +to create the server credential based upon alts. + +On client side, first call +[`alts.DefaultClientOptions`](https://godoc.org/google.golang.org/grpc/credentials/alts#DefaultClientOptions) +to get the configuration for alts and then provide the configuration to +[`alts.NewClientCreds`](https://godoc.org/google.golang.org/grpc/credentials/alts#NewClientCreds) +to create the client credential based upon alts. + +Next, same as TLS, start the server with the server credential and let client +dial to server with the client credential. + +Finally, make an RPC to test the secure connection based upon ALTS is +successfully up. \ No newline at end of file diff --git a/examples/features/encryption/TLS/client/main.go b/examples/features/encryption/TLS/client/main.go new file mode 100644 index 000000000000..eeda118f14f1 --- /dev/null +++ b/examples/features/encryption/TLS/client/main.go @@ -0,0 +1,67 @@ +/* + * + * Copyright 2018 gRPC 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 main + +import ( + "context" + "fmt" + "log" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + pb "google.golang.org/grpc/examples/helloworld/helloworld" + "google.golang.org/grpc/testdata" +) + +const ( + address = "localhost:50051" +) + +// callSayHello calls SayHello on c with the given name, and prints the +// response. +func callSayHello(c pb.GreeterClient, name string) { + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name}) + if err != nil { + log.Fatalf("client.SayHello(_) = _, %v", err) + } + fmt.Println("Greeting: ", r.Message) +} + +func main() { + // Create tls based credential. + creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com") + if err != nil { + log.Fatalf("failed to load credentials: %v", err) + } + + // Set up a connection to the server. + conn, err := grpc.Dial(address, grpc.WithTransportCredentials(creds)) + if err != nil { + log.Fatalf("did not connect: %v", err) + } + defer conn.Close() + + fmt.Println("--- calling helloworld.Greeter/SayHello ---") + // Make a greeter client and send an RPC. + hwc := pb.NewGreeterClient(conn) + callSayHello(hwc, "world") +} diff --git a/examples/features/encryption/TLS/server/main.go b/examples/features/encryption/TLS/server/main.go new file mode 100644 index 000000000000..f59848b2367f --- /dev/null +++ b/examples/features/encryption/TLS/server/main.go @@ -0,0 +1,64 @@ +/* + * + * Copyright 2018 gRPC 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 main + +import ( + "context" + "log" + "net" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + pb "google.golang.org/grpc/examples/helloworld/helloworld" + "google.golang.org/grpc/testdata" +) + +const ( + port = ":50051" +) + +// hwServer is used to implement helloworld.GreeterServer. +type hwServer struct{} + +// SayHello implements helloworld.GreeterServer +func (s *hwServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { + return &pb.HelloReply{Message: "Hello " + in.Name}, nil +} + +func main() { + lis, err := net.Listen("tcp", port) + if err != nil { + log.Fatalf("failed to listen: %v", err) + } + + // Create tls based credential. + creds, err := credentials.NewServerTLSFromFile(testdata.Path("server1.pem"), testdata.Path("server1.key")) + if err != nil { + log.Fatalf("failed to create credentials: %v", err) + } + + s := grpc.NewServer(grpc.Creds(creds)) + + // Register Greeter on the server. + pb.RegisterGreeterServer(s, &hwServer{}) + + if err := s.Serve(lis); err != nil { + log.Fatalf("failed to serve: %v", err) + } +} From 25c353cc76d5ab7b04702ecd97d60ced573c1c5c Mon Sep 17 00:00:00 2001 From: Yuxuan Li Date: Wed, 19 Dec 2018 14:12:29 -0800 Subject: [PATCH 2/2] fix reviews --- .../features/encryption/ALTS/client/main.go | 31 +++++++-------- .../features/encryption/ALTS/server/main.go | 39 +++++++++++++------ .../features/encryption/TLS/client/main.go | 31 +++++++-------- .../features/encryption/TLS/server/main.go | 39 +++++++++++++------ 4 files changed, 84 insertions(+), 56 deletions(-) diff --git a/examples/features/encryption/ALTS/client/main.go b/examples/features/encryption/ALTS/client/main.go index 50bde879cc4c..aa090807ba34 100644 --- a/examples/features/encryption/ALTS/client/main.go +++ b/examples/features/encryption/ALTS/client/main.go @@ -16,48 +16,47 @@ * */ +// Binary client is an example client. package main import ( "context" + "flag" "fmt" "log" "time" "google.golang.org/grpc" "google.golang.org/grpc/credentials/alts" - pb "google.golang.org/grpc/examples/helloworld/helloworld" + ecpb "google.golang.org/grpc/examples/features/proto/echo" ) -const ( - address = "localhost:50051" -) +var addr = flag.String("addr", "localhost:50051", "the address to connect to") -// callSayHello calls SayHello on c with the given name, and prints the -// response. -func callSayHello(c pb.GreeterClient, name string) { - ctx, cancel := context.WithTimeout(context.Background(), time.Second) +func callUnaryEcho(client ecpb.EchoClient, message string) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name}) + resp, err := client.UnaryEcho(ctx, &ecpb.EchoRequest{Message: message}) if err != nil { - log.Fatalf("client.SayHello(_) = _, %v", err) + log.Fatalf("client.UnaryEcho(_) = _, %v: ", err) } - fmt.Println("Greeting: ", r.Message) + fmt.Println("UnaryEcho: ", resp.Message) } func main() { + flag.Parse() + // Create alts based credential. altsTC := alts.NewClientCreds(alts.DefaultClientOptions()) // Set up a connection to the server. - conn, err := grpc.Dial(address, grpc.WithTransportCredentials(altsTC)) + conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(altsTC)) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() - fmt.Println("--- calling helloworld.Greeter/SayHello ---") - // Make a greeter client and send an RPC. - hwc := pb.NewGreeterClient(conn) - callSayHello(hwc, "world") + // Make a echo client and send an RPC. + rgc := ecpb.NewEchoClient(conn) + callUnaryEcho(rgc, "hello world") } diff --git a/examples/features/encryption/ALTS/server/main.go b/examples/features/encryption/ALTS/server/main.go index 4fc3dbf24b09..f4b84d72f67f 100644 --- a/examples/features/encryption/ALTS/server/main.go +++ b/examples/features/encryption/ALTS/server/main.go @@ -16,32 +16,47 @@ * */ +// Binary server is an example server. package main import ( "context" + "flag" + "fmt" "log" "net" "google.golang.org/grpc" + "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials/alts" - pb "google.golang.org/grpc/examples/helloworld/helloworld" + ecpb "google.golang.org/grpc/examples/features/proto/echo" + "google.golang.org/grpc/status" ) -const ( - port = ":50051" -) +var port = flag.Int("port", 50051, "the port to serve on") + +type ecServer struct{} + +func (s *ecServer) UnaryEcho(ctx context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) { + return &ecpb.EchoResponse{Message: req.Message}, nil +} -// hwServer is used to implement helloworld.GreeterServer. -type hwServer struct{} +func (s *ecServer) ServerStreamingEcho(*ecpb.EchoRequest, ecpb.Echo_ServerStreamingEchoServer) error { + return status.Errorf(codes.Unimplemented, "not implemented") +} + +func (s *ecServer) ClientStreamingEcho(ecpb.Echo_ClientStreamingEchoServer) error { + return status.Errorf(codes.Unimplemented, "not implemented") +} -// SayHello implements helloworld.GreeterServer -func (s *hwServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { - return &pb.HelloReply{Message: "Hello " + in.Name}, nil +func (s *ecServer) BidirectionalStreamingEcho(ecpb.Echo_BidirectionalStreamingEchoServer) error { + return status.Errorf(codes.Unimplemented, "not implemented") } func main() { - lis, err := net.Listen("tcp", port) + flag.Parse() + + lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port)) if err != nil { log.Fatalf("failed to listen: %v", err) } @@ -50,8 +65,8 @@ func main() { s := grpc.NewServer(grpc.Creds(altsTC)) - // Register Greeter on the server. - pb.RegisterGreeterServer(s, &hwServer{}) + // Register EchoServer on the server. + ecpb.RegisterEchoServer(s, &ecServer{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/examples/features/encryption/TLS/client/main.go b/examples/features/encryption/TLS/client/main.go index eeda118f14f1..3cac02113a7f 100644 --- a/examples/features/encryption/TLS/client/main.go +++ b/examples/features/encryption/TLS/client/main.go @@ -16,37 +16,37 @@ * */ +// Binary client is an example client. package main import ( "context" + "flag" "fmt" "log" "time" "google.golang.org/grpc" "google.golang.org/grpc/credentials" - pb "google.golang.org/grpc/examples/helloworld/helloworld" + ecpb "google.golang.org/grpc/examples/features/proto/echo" "google.golang.org/grpc/testdata" ) -const ( - address = "localhost:50051" -) +var addr = flag.String("addr", "localhost:50051", "the address to connect to") -// callSayHello calls SayHello on c with the given name, and prints the -// response. -func callSayHello(c pb.GreeterClient, name string) { - ctx, cancel := context.WithTimeout(context.Background(), time.Second) +func callUnaryEcho(client ecpb.EchoClient, message string) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() - r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name}) + resp, err := client.UnaryEcho(ctx, &ecpb.EchoRequest{Message: message}) if err != nil { - log.Fatalf("client.SayHello(_) = _, %v", err) + log.Fatalf("client.UnaryEcho(_) = _, %v: ", err) } - fmt.Println("Greeting: ", r.Message) + fmt.Println("UnaryEcho: ", resp.Message) } func main() { + flag.Parse() + // Create tls based credential. creds, err := credentials.NewClientTLSFromFile(testdata.Path("ca.pem"), "x.test.youtube.com") if err != nil { @@ -54,14 +54,13 @@ func main() { } // Set up a connection to the server. - conn, err := grpc.Dial(address, grpc.WithTransportCredentials(creds)) + conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(creds)) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() - fmt.Println("--- calling helloworld.Greeter/SayHello ---") - // Make a greeter client and send an RPC. - hwc := pb.NewGreeterClient(conn) - callSayHello(hwc, "world") + // Make a echo client and send an RPC. + rgc := ecpb.NewEchoClient(conn) + callUnaryEcho(rgc, "hello world") } diff --git a/examples/features/encryption/TLS/server/main.go b/examples/features/encryption/TLS/server/main.go index f59848b2367f..538a2b87d650 100644 --- a/examples/features/encryption/TLS/server/main.go +++ b/examples/features/encryption/TLS/server/main.go @@ -16,33 +16,48 @@ * */ +// Binary server is an example server. package main import ( "context" + "flag" + "fmt" "log" "net" "google.golang.org/grpc" + "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" - pb "google.golang.org/grpc/examples/helloworld/helloworld" + ecpb "google.golang.org/grpc/examples/features/proto/echo" + "google.golang.org/grpc/status" "google.golang.org/grpc/testdata" ) -const ( - port = ":50051" -) +var port = flag.Int("port", 50051, "the port to serve on") + +type ecServer struct{} + +func (s *ecServer) UnaryEcho(ctx context.Context, req *ecpb.EchoRequest) (*ecpb.EchoResponse, error) { + return &ecpb.EchoResponse{Message: req.Message}, nil +} -// hwServer is used to implement helloworld.GreeterServer. -type hwServer struct{} +func (s *ecServer) ServerStreamingEcho(*ecpb.EchoRequest, ecpb.Echo_ServerStreamingEchoServer) error { + return status.Errorf(codes.Unimplemented, "not implemented") +} + +func (s *ecServer) ClientStreamingEcho(ecpb.Echo_ClientStreamingEchoServer) error { + return status.Errorf(codes.Unimplemented, "not implemented") +} -// SayHello implements helloworld.GreeterServer -func (s *hwServer) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { - return &pb.HelloReply{Message: "Hello " + in.Name}, nil +func (s *ecServer) BidirectionalStreamingEcho(ecpb.Echo_BidirectionalStreamingEchoServer) error { + return status.Errorf(codes.Unimplemented, "not implemented") } func main() { - lis, err := net.Listen("tcp", port) + flag.Parse() + + lis, err := net.Listen("tcp", fmt.Sprintf(":%d", *port)) if err != nil { log.Fatalf("failed to listen: %v", err) } @@ -55,8 +70,8 @@ func main() { s := grpc.NewServer(grpc.Creds(creds)) - // Register Greeter on the server. - pb.RegisterGreeterServer(s, &hwServer{}) + // Register EchoServer on the server. + ecpb.RegisterEchoServer(s, &ecServer{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err)