...

Source file src/github.com/GoogleCloudPlatform/k8s-config-connector/pkg/webhook/cert/generator/util.go

Documentation: github.com/GoogleCloudPlatform/k8s-config-connector/pkg/webhook/cert/generator

     1  /*
     2  Copyright 2018 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package generator
    18  
    19  import (
    20  	"crypto/tls"
    21  	"crypto/x509"
    22  	"encoding/pem"
    23  	"time"
    24  )
    25  
    26  // ValidCACert think cert and key are valid if they meet the following requirements:
    27  // - key and cert are valid pair
    28  // - caCert is the root ca of cert
    29  // - cert is for dnsName
    30  // - cert won't expire before time
    31  func ValidCACert(key, cert, caCert []byte, dnsName string, time time.Time) bool {
    32  	if len(key) == 0 || len(cert) == 0 || len(caCert) == 0 {
    33  		return false
    34  	}
    35  	// Verify key and cert are valid pair
    36  	_, err := tls.X509KeyPair(cert, key)
    37  	if err != nil {
    38  		return false
    39  	}
    40  
    41  	// Verify cert is valid for at least 1 year.
    42  	pool := x509.NewCertPool()
    43  	if !pool.AppendCertsFromPEM(caCert) {
    44  		return false
    45  	}
    46  	block, _ := pem.Decode([]byte(cert))
    47  	if block == nil {
    48  		return false
    49  	}
    50  	c, err := x509.ParseCertificate(block.Bytes)
    51  	if err != nil {
    52  		return false
    53  	}
    54  	ops := x509.VerifyOptions{
    55  		DNSName:     dnsName,
    56  		Roots:       pool,
    57  		CurrentTime: time,
    58  	}
    59  	_, err = c.Verify(ops)
    60  	return err == nil
    61  }
    62  

View as plain text