Skip to content

Commit

Permalink
example: add mutual TLS example (#5194)
Browse files Browse the repository at this point in the history
  • Loading branch information
sding3 authored Feb 24, 2022
1 parent e601f1a commit 328efcc
Show file tree
Hide file tree
Showing 6 changed files with 301 additions and 1 deletion.
35 changes: 35 additions & 0 deletions examples/data/x509/client_ca_cert.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
-----BEGIN CERTIFICATE-----
MIIGAjCCA+qgAwIBAgIUZzkKhtgm6Y3RaksChHMIJFKV+U4wDQYJKoZIhvcNAQEL
BQAwUDELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQwwCgYDVQQHDANTVkwxDTAL
BgNVBAoMBGdSUEMxFzAVBgNVBAMMDnRlc3QtY2xpZW50X2NhMB4XDTIxMTIyMzE4
NDI1MFoXDTMxMTIyMTE4NDI1MFowUDELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNB
MQwwCgYDVQQHDANTVkwxDTALBgNVBAoMBGdSUEMxFzAVBgNVBAMMDnRlc3QtY2xp
ZW50X2NhMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA1Rk7zsuwXn8r
KMHk+gmvaftFmlY+NHs1mKJPzyCGFnablnJtHU4hDpSvvNitoQ0OcurOo9V9ALlA
U2uw/1q6Yhg1Am4cXwSWHG0/GwCQAdPTVb7W1MiAd/IB5bx9xrwfjrpGLjVLS3/y
nOKP+kl1bf6WAcLEPClvH+kSG8xMwvg58ot7ipWQcWBTSuZLaz89d2yfxpvtwrvS
YDemY6f8Tkxil+kDjb2Jo/zdRDz8eIEOs1PcdztrdWWeQaYJVX6aEOHCfdVNOHw3
jNQKyVREUgXjr/pkwo9fTnZjQdBUhZIo7NuPPG25t5qZK3dUDuLcVRQ5Vt0/45pZ
/HkZDCkxmSynZWz2gPClOHVPOG8Eqi0Mbd3XxQSsd1Go667oFotLvTuynbYhdh4s
xAJWXbFV26HgDXI5wXueXrs1n0stUlbD6KahfeoYBu+idX7gB4Rftqhqlb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7SVpxpjcr3OZdh05T+heCVuPp+9mHBmcxbeA8rkMZAq
vILLwgwEriSbKy9Y1GLs2oaPNaWEpN9Q6kZPUwtwlzjHG3OOtldeXPpMVpg6Sb0y
3NnRfvfV/g2gm68S21j6qhGM2aeQCdCu5insqnR8GS5/stmuyCNnlst24JBneE0i
louEQ0EV
-----END CERTIFICATE-----
32 changes: 32 additions & 0 deletions examples/data/x509/client_cert.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
-----BEGIN CERTIFICATE-----
MIIFcTCCA1mgAwIBAgICA+gwDQYJKoZIhvcNAQELBQAwUDELMAkGA1UEBhMCVVMx
CzAJBgNVBAgMAkNBMQwwCgYDVQQHDANTVkwxDTALBgNVBAoMBGdSUEMxFzAVBgNV
BAMMDnRlc3QtY2xpZW50X2NhMB4XDTIxMTIyMzE4NDI1MVoXDTMxMTIyMTE4NDI1
MVowTjELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMQwwCgYDVQQHDANTVkwxDTAL
BgNVBAoMBGdSUEMxFTATBgNVBAMMDHRlc3QtY2xpZW50MTCCAiIwDQYJKoZIhvcN
AQEBBQADggIPADCCAgoCggIBALUoje/J3uPOJ0dapY2s7mGLVPhYRaHyRnJE2/TY
zFOB0IisAF3R7BIDufQrHhk3fh0JazCw95TDD9rxsKEVs6Z50lmDkrg/bjlsniE/
n+M1JacaLQW7xfh2L+Ei4jvMr101nAsimd6IxFU9m3+2SFbhPBG/GWWJ2ZKqQblz
DVMpNg9FYNmMe45vLevOhdPQBE4cVoAPhI9Je+P4Koslebhor0koUeQVeYdBbCq3
3dQJPAHjBST6mD9mJI4yVrE3Xso3LO85WROUPhRYQyXhrgU15W6g9qTpMTfkriUe
FYLCtAPU9LBodyvjYLuwoEoyRVsA6Zh/vABteD8Afl552fV9KwN2fRVbTDAxQCp7
P8gE3/rD1RKv7KBNJ/LrwMu7g4VO+tzYDxWee+eXPQ6M/zRWAb3E0v3UNHsF1ZBl
rlFhEiRShHrXD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CQU1aVNJnujRKFyhd07sEjxsad9
Bn/aYes=
-----END CERTIFICATE-----
51 changes: 51 additions & 0 deletions examples/data/x509/client_key.pem
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
-----BEGIN RSA PRIVATE KEY-----
MIIJKgIBAAKCAgEAtSiN78ne484nR1qljazuYYtU+FhFofJGckTb9NjMU4HQiKwA
XdHsEgO59CseGTd+HQlrMLD3lMMP2vGwoRWzpnnSWYOSuD9uOWyeIT+f4zUlpxot
BbvF+HYv4SLiO8yvXTWcCyKZ3ojEVT2bf7ZIVuE8Eb8ZZYnZkqpBuXMNUyk2D0Vg
2Yx7jm8t686F09AEThxWgA+Ej0l74/gqiyV5uGivSShR5BV5h0FsKrfd1Ak8AeMF
JPqYP2YkjjJWsTdeyjcs7zlZE5Q+FFhDJeGuBTXlbqD2pOkxN+SuJR4VgsK0A9T0
sGh3K+Ngu7CgSjJFWwDpmH+8AG14PwB+XnnZ9X0rA3Z9FVtMMDFAKns/yATf+sPV
Eq/soE0n8uvAy7uDhU763NgPFZ5755c9Doz/NFYBvcTS/dQ0ewXVkGWuUWESJFKE
etcMQoxDAJNKtGPBhqNSln8erZRIOCQt6kqZOYJqgF9Yc/JnBuWpJOcDgM06Hk3b
d4nKsuck49iPNmoQ99fmENOMVF1VNDG2ZiUnWa7C2U3K7BkMiaGM7obnik+P9tXq
DLX5ikhAF6Y+he2qqZxGIRVZJXnMCLPBFpZ/zm2qnFvVOO6PY6kP2V6g7glfQcuO
HJAGgqyk2iG7Yjj6zt7H/D3Zt/vpxOlhNswmoinfthmZ89XO0dVoyXhbTFECAwEA
AQKCAgEAjtzrijWVy+sQuMm4k1DUMSKzIKJkT4GDoqvBFoc+I4DVVmLmaxaYZ+B+
bhruwo4rq3R5Ds4QgUWPJGfDllVJ9rhNdYA4XYrQPwL0dV36ljCcf/o5lTLuvbFe
stpStTwG86fKZlGkLIWI53wNPBshUzqOp6QfwB6E8Y/JAxnDYVi3pDVfWlDaQ4pU
GYkl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UHKKbd5U15y1NV1BQloaPJLwpPAVTkBszQSHanltN
l9POJBJlfQ1eWL88wHdKiLbtOg6PTfAmfghIRxakjHvxBgFO1/xG6Lxm7QwUDQ==
-----END RSA PRIVATE KEY-----
21 changes: 20 additions & 1 deletion examples/features/encryption/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,23 @@ 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.
successfully up.

### mTLS

In mutual TLS (mTLS), the client and the server authenticate each other. gRPC
allows users to configure mutual TLS at the connection level.

In normal TLS, the server is only concerned with presenting the server
certificate for clients to verify. In mutual TLS, the server also loads in a
list of trusted CA files for verifying client presented certificates with.
This is done via setting
[`tls.Config.ClientCAs`](https://pkg.go.dev/crypto/tls#Config.ClientCAs)
to the list of trusted CA files,
and setting [`tls.config.ClientAuth`](https://pkg.go.dev/crypto/tls#Config.ClientAuth)
to [`tls.RequireAndVerifyClientCert`](https://pkg.go.dev/crypto/tls#RequireAndVerifyClientCert).

In normal TLS, the client is only concerned with authenticating the server by
using one or more trusted CA file. In mutual TLS, the client also presents its
client certificate to the server for authentication. This is done via setting
[`tls.Config.Certificates`](https://pkg.go.dev/crypto/tls#Config.Certificates).
81 changes: 81 additions & 0 deletions examples/features/encryption/mTLS/client/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
/*
*
* Copyright 2022 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.
*
*/

// Binary client is an example client which connects to the server using mTLS.
package main

import (
"context"
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"log"
"time"

"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/examples/data"
ecpb "google.golang.org/grpc/examples/features/proto/echo"
)

var addr = flag.String("addr", "localhost:50051", "the address to connect to")

func callUnaryEcho(client ecpb.EchoClient, message string) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := client.UnaryEcho(ctx, &ecpb.EchoRequest{Message: message})
if err != nil {
log.Fatalf("client.UnaryEcho(_) = _, %v: ", err)
}
fmt.Println("UnaryEcho: ", resp.Message)
}

func main() {
flag.Parse()

cert, err := tls.LoadX509KeyPair(data.Path("x509/client_cert.pem"), data.Path("x509/client_key.pem"))
if err != nil {
log.Fatalf("failed to load client cert: %v", err)
}

ca := x509.NewCertPool()
caFilePath := data.Path("x509/ca_cert.pem")
caBytes, err := ioutil.ReadFile(caFilePath)
if err != nil {
log.Fatalf("failed to read ca cert %q: %v", caFilePath, err)
}
if ok := ca.AppendCertsFromPEM(caBytes); !ok {
log.Fatalf("failed to parse %q", caFilePath)
}

tlsConfig := &tls.Config{
ServerName: "x.test.example.com",
Certificates: []tls.Certificate{cert},
RootCAs: ca,
}

conn, err := grpc.Dial(*addr, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()

callUnaryEcho(ecpb.NewEchoClient(conn), "hello world")
}
82 changes: 82 additions & 0 deletions examples/features/encryption/mTLS/server/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
*
* Copyright 2022 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.
*
*/

// Binary server is an example server which authenticates clients using mTLS.
package main

import (
"context"
"crypto/tls"
"crypto/x509"
"flag"
"fmt"
"io/ioutil"
"log"
"net"

"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/examples/data"
pb "google.golang.org/grpc/examples/features/proto/echo"
)

var port = flag.Int("port", 50051, "the port to serve on")

type ecServer struct {
pb.UnimplementedEchoServer
}

func (s *ecServer) UnaryEcho(ctx context.Context, req *pb.EchoRequest) (*pb.EchoResponse, error) {
return &pb.EchoResponse{Message: req.Message}, nil
}

func main() {
flag.Parse()
log.Printf("server starting on port %d...\n", *port)

cert, err := tls.LoadX509KeyPair(data.Path("x509/server_cert.pem"), data.Path("x509/server_key.pem"))
if err != nil {
log.Fatalf("failed to load key pair: %s", err)
}

ca := x509.NewCertPool()
caFilePath := data.Path("x509/client_ca_cert.pem")
caBytes, err := ioutil.ReadFile(caFilePath)
if err != nil {
log.Fatalf("failed to read ca cert %q: %v", caFilePath, err)
}
if ok := ca.AppendCertsFromPEM(caBytes); !ok {
log.Fatalf("failed to parse %q", caFilePath)
}

tlsConfig := &tls.Config{
ClientAuth: tls.RequireAndVerifyClientCert,
Certificates: []tls.Certificate{cert},
ClientCAs: ca,
}

s := grpc.NewServer(grpc.Creds(credentials.NewTLS(tlsConfig)))
pb.RegisterEchoServer(s, &ecServer{})
lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}

0 comments on commit 328efcc

Please sign in to comment.