server.go 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. package main
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "log"
  10. "net"
  11. "sync"
  12. "time"
  13. "google.golang.org/grpc"
  14. "google.golang.org/grpc/credentials"
  15. "google.golang.org/grpc/peer"
  16. "github.com/smallstep/certificates/autocert/examples/hello-mtls/go-grpc/hello"
  17. )
  18. const (
  19. autocertFile = "/var/run/autocert.step.sm/site.crt"
  20. autocertKey = "/var/run/autocert.step.sm/site.key"
  21. autocertRoot = "/var/run/autocert.step.sm/root.crt"
  22. tickFrequency = 15 * time.Second
  23. )
  24. // Uses techniques from https://diogomonica.com/2017/01/11/hitless-tls-certificate-rotation-in-go/
  25. // to automatically rotate certificates when they're renewed.
  26. type rotator struct {
  27. sync.RWMutex
  28. certificate *tls.Certificate
  29. }
  30. func (r *rotator) getCertificate(hello *tls.ClientHelloInfo) (*tls.Certificate, error) {
  31. r.RLock()
  32. defer r.RUnlock()
  33. return r.certificate, nil
  34. }
  35. func (r *rotator) loadCertificate(certFile, keyFile string) error {
  36. r.Lock()
  37. defer r.Unlock()
  38. c, err := tls.LoadX509KeyPair(certFile, keyFile)
  39. if err != nil {
  40. return err
  41. }
  42. r.certificate = &c
  43. return nil
  44. }
  45. func loadRootCertPool() (*x509.CertPool, error) {
  46. root, err := ioutil.ReadFile(autocertRoot)
  47. if err != nil {
  48. return nil, err
  49. }
  50. pool := x509.NewCertPool()
  51. if ok := pool.AppendCertsFromPEM(root); !ok {
  52. return nil, errors.New("Missing or invalid root certificate")
  53. }
  54. return pool, nil
  55. }
  56. // Greeter is a service that sends greetings.
  57. type Greeter struct{}
  58. // SayHello sends a greeting
  59. func (g *Greeter) SayHello(ctx context.Context, in *hello.HelloRequest) (*hello.HelloReply, error) {
  60. return &hello.HelloReply{Message: "Hello " + in.Name + " (" + getServerName(ctx) + ")"}, nil
  61. }
  62. // SayHelloAgain sends another greeting
  63. func (g *Greeter) SayHelloAgain(ctx context.Context, in *hello.HelloRequest) (*hello.HelloReply, error) {
  64. return &hello.HelloReply{Message: "Hello again " + in.Name + " (" + getServerName(ctx) + ")"}, nil
  65. }
  66. func getServerName(ctx context.Context) string {
  67. if p, ok := peer.FromContext(ctx); ok {
  68. if tlsInfo, ok := p.AuthInfo.(credentials.TLSInfo); ok {
  69. return tlsInfo.State.ServerName
  70. }
  71. }
  72. return "unknown"
  73. }
  74. func main() {
  75. roots, err := loadRootCertPool()
  76. if err != nil {
  77. log.Fatal(err)
  78. }
  79. // Load certificate
  80. r := &rotator{}
  81. if err := r.loadCertificate(autocertFile, autocertKey); err != nil {
  82. log.Fatal("error loading certificate and key", err)
  83. }
  84. tlsConfig := &tls.Config{
  85. ClientAuth: tls.RequireAndVerifyClientCert,
  86. ClientCAs: roots,
  87. MinVersion: tls.VersionTLS12,
  88. CurvePreferences: []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
  89. PreferServerCipherSuites: true,
  90. CipherSuites: []uint16{
  91. tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
  92. tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
  93. },
  94. GetCertificate: r.getCertificate,
  95. }
  96. // Schedule periodic re-load of certificate
  97. // A real implementation can use something like
  98. // https://github.com/fsnotify/fsnotify
  99. done := make(chan struct{})
  100. go func() {
  101. ticker := time.NewTicker(tickFrequency)
  102. defer ticker.Stop()
  103. for {
  104. select {
  105. case <-ticker.C:
  106. fmt.Println("Checking for new certificate...")
  107. err := r.loadCertificate(autocertFile, autocertKey)
  108. if err != nil {
  109. log.Println("Error loading certificate and key", err)
  110. }
  111. case <-done:
  112. return
  113. }
  114. }
  115. }()
  116. defer close(done)
  117. lis, err := net.Listen("tcp", ":443")
  118. if err != nil {
  119. log.Fatalf("failed to listen: %v", err)
  120. }
  121. srv := grpc.NewServer(grpc.Creds(credentials.NewTLS(tlsConfig)))
  122. hello.RegisterGreeterServer(srv, &Greeter{})
  123. log.Println("Listening on :443")
  124. if err := srv.Serve(lis); err != nil {
  125. log.Fatalf("failed to serve: %v", err)
  126. }
  127. }