istio.io/istio@v0.0.0-20240520182934-d79c90f27776/pkg/webhooks/util/util.go (about)

     1  // Copyright Istio Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package util
    16  
    17  import (
    18  	"crypto/x509"
    19  	"encoding/pem"
    20  	"errors"
    21  	"fmt"
    22  
    23  	"istio.io/istio/pilot/pkg/keycertbundle"
    24  )
    25  
    26  type ConfigError struct {
    27  	err    error
    28  	reason string
    29  }
    30  
    31  func (e ConfigError) Error() string {
    32  	return e.err.Error()
    33  }
    34  
    35  func (e ConfigError) Reason() string {
    36  	return e.reason
    37  }
    38  
    39  func LoadCABundle(caBundleWatcher *keycertbundle.Watcher) ([]byte, error) {
    40  	caBundle := caBundleWatcher.GetCABundle()
    41  	if err := VerifyCABundle(caBundle); err != nil {
    42  		return nil, &ConfigError{err, "could not verify caBundle"}
    43  	}
    44  
    45  	return caBundle, nil
    46  }
    47  
    48  func VerifyCABundle(caBundle []byte) error {
    49  	block, _ := pem.Decode(caBundle)
    50  	if block == nil {
    51  		return errors.New("could not decode pem")
    52  	}
    53  	if block.Type != "CERTIFICATE" {
    54  		return fmt.Errorf("cert contains wrong pem type: %q", block.Type)
    55  	}
    56  	if _, err := x509.ParseCertificate(block.Bytes); err != nil {
    57  		return fmt.Errorf("cert contains invalid x509 certificate: %v", err)
    58  	}
    59  	return nil
    60  }