Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

advancedtls: add PEMFileProvider implementation for on-file-change credential reloading #3826

Merged
merged 6 commits into from
Sep 2, 2020
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
179 changes: 179 additions & 0 deletions security/advancedtls/pemfile_provider.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
/*
*
* Copyright 2020 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 advancedtls

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

"google.golang.org/grpc/credentials/tls/certprovider"
"google.golang.org/grpc/grpclog"
)

var defaultIdentityInterval = 1 * time.Hour
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
var defaultRootInterval = 2 * time.Hour

var readKeyCertPairFunc = tls.LoadX509KeyPair
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved

var readTrustCertFunc = func(trustFile string) (*x509.CertPool, error) {
trustData, err := ioutil.ReadFile(trustFile)
if err != nil {
return nil, err
}
trustPool := x509.NewCertPool()
ok := trustPool.AppendCertsFromPEM(trustData)
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
if !ok {
return nil, fmt.Errorf("failed to call AppendCertsFromPEM")
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
}
return trustPool, nil
}

var logger = grpclog.Component("advancedtls")

// PEMFileProviderOptions contains options to configure a PEMFileProvider.
// Note that these fields will only take effect in construction time. Once the PEMFileProvider starts, changing fields in PEMFileProviderOptions will do nothing.
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
type PEMFileProviderOptions struct {
// CertFile is the file path that holds identity certificate whose updates will be captured by a watching goroutine.
// Optional. If this is set, KeyFile must also be set.
CertFile string
// KeyFile is the file path that holds identity private key whose updates will be captured by a watching goroutine.
// Optional. If this is set, CertFile must also be set.
KeyFile string
// TrustFile is the file path that holds trust certificate whose updates will be captured by a watching goroutine.
// Optional.
TrustFile string
// IdentityInterval is the time duration between two credential update checks for identity certs.
// Optional. If not set, we will use the default interval.
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
IdentityInterval *time.Duration
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
// RootInterval is the time duration between two credential update checks for root certs.
// Optional. If not set, we will use the default interval.
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
RootInterval *time.Duration
}

// PEMFileProvider implements certprovider.Provider.
// It provides the most up-to-date identity private key-cert pairs and/or root certificates.
type PEMFileProvider struct {
identityDistributor *certprovider.Distributor
rootDistributor *certprovider.Distributor
cancel context.CancelFunc
}

// NewPEMFileProvider uses PEMFileProviderOptions to construct a PEMFileProvider.
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
func NewPEMFileProvider(o *PEMFileProviderOptions) (*PEMFileProvider, error) {
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
if o.CertFile == "" && o.KeyFile == "" && o.TrustFile == "" {
return nil, fmt.Errorf("at least one credential file needs to be specified")
}
if keySpecified, certSpecified := o.KeyFile != "", o.CertFile != ""; keySpecified != certSpecified {
return nil, fmt.Errorf("private key file and identity cert file should be both specified or not specified")
}
if o.IdentityInterval == nil {
o.IdentityInterval = &defaultIdentityInterval
}
if o.RootInterval == nil {
o.RootInterval = &defaultRootInterval
}
provider := &PEMFileProvider{}
if o.CertFile != "" && o.KeyFile != "" {
provider.identityDistributor = certprovider.NewDistributor()
}
if o.TrustFile != "" {
provider.rootDistributor = certprovider.NewDistributor()
}
// A goroutine to pull file changes.
identityTicker := time.NewTicker(*o.IdentityInterval)
rootTicker := time.NewTicker(*o.RootInterval)
ctx, cancel := context.WithCancel(context.Background())
// We pass a copy of PEMFileProviderOptions to the goroutine in case users change it after we start reloading.
go func(ctx context.Context, o PEMFileProviderOptions) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both the context and the options struct need not be passed to the goroutine.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to confirm, we don't want users to be able to change interval values after our application starts. This can't happen with the latest code, because in NewPemFileProvider function we are not accepting a pointer of PEMFileProviderOptions, which will force a copy of PEMFileProviderOptions. Is that right?

for {
select {
case <-ctx.Done():
identityTicker.Stop()
rootTicker.Stop()
return
case <-identityTicker.C:
if provider.identityDistributor == nil {
continue
}
// Read identity certs from PEM files.
identityCert, err := readKeyCertPairFunc(o.CertFile, o.KeyFile)
if err != nil {
// If the reading produces an error, we will skip the update for this round and log the error.
logger.Warningf("tls.LoadX509KeyPair reads %s and %s failed: %v", o.CertFile, o.KeyFile, err)
continue
}
provider.identityDistributor.Set(&certprovider.KeyMaterial{Certs: []tls.Certificate{identityCert}}, nil)
case <-rootTicker.C:
if provider.rootDistributor == nil {
continue
}
// Read root certs from PEM files.
trustPool, err := readTrustCertFunc(o.TrustFile)
if err != nil {
// If the reading produces an error, we will skip the update for this round and log the error.
logger.Warningf("readTrustCertFunc reads %v failed: %v", o.TrustFile, err)
continue
}
provider.rootDistributor.Set(&certprovider.KeyMaterial{Roots: trustPool}, nil)
default:
}
}
}(ctx, *o)
provider.cancel = cancel
return provider, nil
}

// KeyMaterial returns the key material sourced by the PEMFileProvider.
// Callers are expected to use the returned value as read-only.
func (p *PEMFileProvider) KeyMaterial(ctx context.Context) (*certprovider.KeyMaterial, error) {
km := certprovider.KeyMaterial{}
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
if p.identityDistributor == nil && p.rootDistributor == nil {
ZhenLian marked this conversation as resolved.
Show resolved Hide resolved
return nil, fmt.Errorf("no reloading file path specified")
}
if p.identityDistributor != nil {
identityKM, err := p.identityDistributor.KeyMaterial(ctx)
if err != nil {
return nil, err
}
km.Certs = identityKM.Certs
}
if p.rootDistributor != nil {
rootKM, err := p.rootDistributor.KeyMaterial(ctx)
if err != nil {
return nil, err
}
km.Roots = rootKM.Roots
}
return &km, nil
}

// Close cleans up resources allocated by the PEMFileProvider.
func (p *PEMFileProvider) Close() {
p.cancel()
if p.identityDistributor != nil {
p.identityDistributor.Stop()
}
if p.rootDistributor != nil {
p.rootDistributor.Stop()
}
}
Loading