istio.io/istio@v0.0.0-20240520182934-d79c90f27776/security/pkg/nodeagent/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  	"bytes"
    19  	"crypto/x509"
    20  	"encoding/pem"
    21  	"fmt"
    22  	"os"
    23  	"path"
    24  	"time"
    25  
    26  	"istio.io/istio/pkg/env"
    27  	"istio.io/istio/pkg/file"
    28  )
    29  
    30  var k8sInCluster = env.Register("KUBERNETES_SERVICE_HOST", "",
    31  	"Kubernetes service host, set automatically when running in-cluster")
    32  
    33  // ParseCertAndGetExpiryTimestamp parses the first certificate in certByte and returns cert expire
    34  // time, or return error if fails to parse certificate.
    35  func ParseCertAndGetExpiryTimestamp(certByte []byte) (time.Time, error) {
    36  	block, _ := pem.Decode(certByte)
    37  	if block == nil {
    38  		return time.Time{}, fmt.Errorf("failed to decode certificate")
    39  	}
    40  	cert, err := x509.ParseCertificate(block.Bytes)
    41  	if err != nil {
    42  		return time.Time{}, fmt.Errorf("failed to parse certificate: %v", err)
    43  	}
    44  	return cert.NotAfter, nil
    45  }
    46  
    47  // OutputKeyCertToDir output the key and certificate to the given directory.
    48  // If directory string is empty, return nil.
    49  func OutputKeyCertToDir(dir string, privateKey, certChain, rootCert []byte) error {
    50  	var err error
    51  	if len(dir) == 0 {
    52  		return nil
    53  	}
    54  
    55  	certFileMode := os.FileMode(0o600)
    56  	if k8sInCluster.Get() != "" {
    57  		// If this is running on k8s, give more permission to the file certs.
    58  		// This is typically used to share the certs with non-proxy containers in the pod which does not run as root or 1337.
    59  		// For example, prometheus server could use proxy provisioned certs to scrape application metrics through mTLS.
    60  		certFileMode = os.FileMode(0o644)
    61  	}
    62  	// Depending on the SDS resource to output, some fields may be nil
    63  	if privateKey == nil && certChain == nil && rootCert == nil {
    64  		return fmt.Errorf("the input private key, cert chain, and root cert are nil")
    65  	}
    66  
    67  	writeIfNotEqual := func(fileName string, newData []byte) error {
    68  		if newData == nil {
    69  			return nil
    70  		}
    71  		oldData, _ := os.ReadFile(path.Join(dir, fileName))
    72  		if !bytes.Equal(oldData, newData) {
    73  			if err := file.AtomicWrite(path.Join(dir, fileName), newData, certFileMode); err != nil {
    74  				return fmt.Errorf("failed to write data to file %v: %v", fileName, err)
    75  			}
    76  		}
    77  		return nil
    78  	}
    79  
    80  	if err = writeIfNotEqual("key.pem", privateKey); err != nil {
    81  		return err
    82  	}
    83  	if err = writeIfNotEqual("cert-chain.pem", certChain); err != nil {
    84  		return err
    85  	}
    86  	if err = writeIfNotEqual("root-cert.pem", rootCert); err != nil {
    87  		return err
    88  	}
    89  	return nil
    90  }