// Package rpctls builds the transport credentials every gRPC hop uses from // certificate files the operator's PKI issues. With no identity configured a // process speaks plaintext, and only over loopback. package rpctls import ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "net" "os" "path/filepath" "strings" "sync" "time" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/peer" ) // Identity is one process's certificate and the CA it trusts. A nil Identity // is the plaintext loopback mode. type Identity struct { pool *x509.CertPool caPEM []byte cert *certFile } // Load reads the CA at caFile and service's key pair from // certDir/.pem and certDir/-key.pem. Both paths empty means // no TLS and returns nil. func Load(caFile, certDir, service string) (*Identity, error) { if caFile == "" && certDir == "" { return nil, nil } if caFile == "" || certDir == "" { return nil, errors.New("tls: ca_file and cert_dir are both required") } caPEM, err := os.ReadFile(caFile) if err != nil { return nil, fmt.Errorf("tls: read CA: %w", err) } pool := x509.NewCertPool() if !pool.AppendCertsFromPEM(caPEM) { return nil, fmt.Errorf("tls: %s holds no PEM certificate", caFile) } cert := &certFile{ certPath: filepath.Join(certDir, service+".pem"), keyPath: filepath.Join(certDir, service+"-key.pem"), } if _, err := cert.get(); err != nil { return nil, err } return &Identity{pool: pool, caPEM: caPEM, cert: cert}, nil } // CAPEM is the CA certificate a container receives to verify the State // Store. Nil in plaintext mode. func (i *Identity) CAPEM() []byte { if i == nil { return nil } return i.caPEM } // ServerOption returns the credentials for a listener on listen. A listener // that accepts calls without a client certificate (the State Store's task // grants) passes optionalClient; every other listener requires one. func (i *Identity) ServerOption(listen string, optionalClient bool) (grpc.ServerOption, error) { if i == nil { if err := requireLoopback(listen); err != nil { return nil, err } return grpc.Creds(insecure.NewCredentials()), nil } auth := tls.RequireAndVerifyClientCert if optionalClient { auth = tls.VerifyClientCertIfGiven } return grpc.Creds(credentials.NewTLS(&tls.Config{ MinVersion: tls.VersionTLS13, GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return i.cert.get() }, ClientCAs: i.pool, ClientAuth: auth, })), nil } // DialOption returns the credentials for dialling server (its certificate // name) at target. The name, not target's host, is verified, so a service is // reachable through any address, relay or proxy. func (i *Identity) DialOption(target, server string) (grpc.DialOption, error) { if i == nil { if err := requireLoopback(target); err != nil { return nil, err } return grpc.WithTransportCredentials(insecure.NewCredentials()), nil } return grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{ MinVersion: tls.VersionTLS13, RootCAs: i.pool, ServerName: server, GetClientCertificate: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { return i.cert.get() }, })), nil } // CAOnlyDialOption dials server trusting caPEM and presenting no // certificate: a container's credentials are its task grant alone. Empty // caPEM is plaintext, loopback only. func CAOnlyDialOption(caPEM []byte, target, server string) (grpc.DialOption, error) { if len(caPEM) == 0 { var none *Identity return none.DialOption(target, server) } pool := x509.NewCertPool() if !pool.AppendCertsFromPEM(caPEM) { return nil, errors.New("tls: CA holds no PEM certificate") } return grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{ MinVersion: tls.VersionTLS13, RootCAs: pool, ServerName: server, })), nil } // PeerService is the service named by the caller's verified certificate, or // "" when it presented none. func PeerService(ctx context.Context) string { p, ok := peer.FromContext(ctx) if !ok { return "" } info, ok := p.AuthInfo.(credentials.TLSInfo) if !ok || len(info.State.VerifiedChains) == 0 || len(info.State.VerifiedChains[0]) == 0 { return "" } if names := info.State.VerifiedChains[0][0].DNSNames; len(names) > 0 { return names[0] } return "" } // Trusted reports whether the caller is a service: it holds a verified // certificate, or reached a plaintext listener, which is loopback only. func Trusted(ctx context.Context) bool { p, ok := peer.FromContext(ctx) if !ok { return false } if _, isTLS := p.AuthInfo.(credentials.TLSInfo); !isTLS { return true } return PeerService(ctx) != "" } func requireLoopback(addr string) error { host, _, err := net.SplitHostPort(addr) if err != nil { return fmt.Errorf("address %q must be host:port: %w", addr, err) } if strings.EqualFold(host, "localhost") { return nil } if ip := net.ParseIP(host); ip != nil && ip.IsLoopback() { return nil } return fmt.Errorf("%q is not loopback; configure [tls] ca_file and cert_dir to serve or dial it", addr) } // certFile reloads a key pair when its certificate file changes, so the // operator's renewal tooling needs no restart. type certFile struct { certPath, keyPath string mu sync.Mutex modified time.Time cert *tls.Certificate } func (c *certFile) get() (*tls.Certificate, error) { info, err := os.Stat(c.certPath) if err != nil { return nil, fmt.Errorf("tls: %w", err) } c.mu.Lock() defer c.mu.Unlock() if c.cert != nil && info.ModTime().Equal(c.modified) { return c.cert, nil } cert, err := tls.LoadX509KeyPair(c.certPath, c.keyPath) if err != nil { if c.cert != nil { // A renewal caught between writing the two files keeps the // previous pair until both match. return c.cert, nil } return nil, fmt.Errorf("tls: load %s: %w", c.certPath, err) } c.cert, c.modified = &cert, info.ModTime() return c.cert, nil }