kubelet.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package certificate
  14. import (
  15. "crypto/tls"
  16. "crypto/x509"
  17. "crypto/x509/pkix"
  18. "fmt"
  19. "net"
  20. "sort"
  21. "github.com/prometheus/client_golang/prometheus"
  22. certificates "k8s.io/api/certificates/v1beta1"
  23. "k8s.io/api/core/v1"
  24. "k8s.io/apimachinery/pkg/types"
  25. clientset "k8s.io/client-go/kubernetes"
  26. certificatesclient "k8s.io/client-go/kubernetes/typed/certificates/v1beta1"
  27. "k8s.io/client-go/util/certificate"
  28. kubeletconfig "k8s.io/kubernetes/pkg/kubelet/apis/config"
  29. "k8s.io/kubernetes/pkg/kubelet/metrics"
  30. )
  31. // NewKubeletServerCertificateManager creates a certificate manager for the kubelet when retrieving a server certificate
  32. // or returns an error.
  33. func NewKubeletServerCertificateManager(kubeClient clientset.Interface, kubeCfg *kubeletconfig.KubeletConfiguration, nodeName types.NodeName, getAddresses func() []v1.NodeAddress, certDirectory string) (certificate.Manager, error) {
  34. var certSigningRequestClient certificatesclient.CertificateSigningRequestInterface
  35. if kubeClient != nil && kubeClient.CertificatesV1beta1() != nil {
  36. certSigningRequestClient = kubeClient.CertificatesV1beta1().CertificateSigningRequests()
  37. }
  38. certificateStore, err := certificate.NewFileStore(
  39. "kubelet-server",
  40. certDirectory,
  41. certDirectory,
  42. kubeCfg.TLSCertFile,
  43. kubeCfg.TLSPrivateKeyFile)
  44. if err != nil {
  45. return nil, fmt.Errorf("failed to initialize server certificate store: %v", err)
  46. }
  47. var certificateExpiration = prometheus.NewGauge(
  48. prometheus.GaugeOpts{
  49. Namespace: metrics.KubeletSubsystem,
  50. Subsystem: "certificate_manager",
  51. Name: "server_expiration_seconds",
  52. Help: "Gauge of the lifetime of a certificate. The value is the date the certificate will expire in seconds since January 1, 1970 UTC.",
  53. },
  54. )
  55. prometheus.MustRegister(certificateExpiration)
  56. getTemplate := func() *x509.CertificateRequest {
  57. hostnames, ips := addressesToHostnamesAndIPs(getAddresses())
  58. // don't return a template if we have no addresses to request for
  59. if len(hostnames) == 0 && len(ips) == 0 {
  60. return nil
  61. }
  62. return &x509.CertificateRequest{
  63. Subject: pkix.Name{
  64. CommonName: fmt.Sprintf("system:node:%s", nodeName),
  65. Organization: []string{"system:nodes"},
  66. },
  67. DNSNames: hostnames,
  68. IPAddresses: ips,
  69. }
  70. }
  71. m, err := certificate.NewManager(&certificate.Config{
  72. ClientFn: func(current *tls.Certificate) (certificatesclient.CertificateSigningRequestInterface, error) {
  73. return certSigningRequestClient, nil
  74. },
  75. GetTemplate: getTemplate,
  76. Usages: []certificates.KeyUsage{
  77. // https://tools.ietf.org/html/rfc5280#section-4.2.1.3
  78. //
  79. // Digital signature allows the certificate to be used to verify
  80. // digital signatures used during TLS negotiation.
  81. certificates.UsageDigitalSignature,
  82. // KeyEncipherment allows the cert/key pair to be used to encrypt
  83. // keys, including the symmetric keys negotiated during TLS setup
  84. // and used for data transfer.
  85. certificates.UsageKeyEncipherment,
  86. // ServerAuth allows the cert to be used by a TLS server to
  87. // authenticate itself to a TLS client.
  88. certificates.UsageServerAuth,
  89. },
  90. CertificateStore: certificateStore,
  91. CertificateExpiration: certificateExpiration,
  92. })
  93. if err != nil {
  94. return nil, fmt.Errorf("failed to initialize server certificate manager: %v", err)
  95. }
  96. return m, nil
  97. }
  98. func addressesToHostnamesAndIPs(addresses []v1.NodeAddress) (dnsNames []string, ips []net.IP) {
  99. seenDNSNames := map[string]bool{}
  100. seenIPs := map[string]bool{}
  101. for _, address := range addresses {
  102. if len(address.Address) == 0 {
  103. continue
  104. }
  105. switch address.Type {
  106. case v1.NodeHostName:
  107. if ip := net.ParseIP(address.Address); ip != nil {
  108. seenIPs[address.Address] = true
  109. } else {
  110. seenDNSNames[address.Address] = true
  111. }
  112. case v1.NodeExternalIP, v1.NodeInternalIP:
  113. if ip := net.ParseIP(address.Address); ip != nil {
  114. seenIPs[address.Address] = true
  115. }
  116. case v1.NodeExternalDNS, v1.NodeInternalDNS:
  117. seenDNSNames[address.Address] = true
  118. }
  119. }
  120. for dnsName := range seenDNSNames {
  121. dnsNames = append(dnsNames, dnsName)
  122. }
  123. for ip := range seenIPs {
  124. ips = append(ips, net.ParseIP(ip))
  125. }
  126. // return in stable order
  127. sort.Strings(dnsNames)
  128. sort.Slice(ips, func(i, j int) bool { return ips[i].String() < ips[j].String() })
  129. return dnsNames, ips
  130. }
  131. // NewKubeletClientCertificateManager sets up a certificate manager without a
  132. // client that can be used to sign new certificates (or rotate). If a CSR
  133. // client is set later, it may begin rotating/renewing the client cert.
  134. func NewKubeletClientCertificateManager(
  135. certDirectory string,
  136. nodeName types.NodeName,
  137. bootstrapCertData []byte,
  138. bootstrapKeyData []byte,
  139. certFile string,
  140. keyFile string,
  141. clientFn certificate.CSRClientFunc,
  142. ) (certificate.Manager, error) {
  143. certificateStore, err := certificate.NewFileStore(
  144. "kubelet-client",
  145. certDirectory,
  146. certDirectory,
  147. certFile,
  148. keyFile)
  149. if err != nil {
  150. return nil, fmt.Errorf("failed to initialize client certificate store: %v", err)
  151. }
  152. var certificateExpiration = prometheus.NewGauge(
  153. prometheus.GaugeOpts{
  154. Namespace: metrics.KubeletSubsystem,
  155. Subsystem: "certificate_manager",
  156. Name: "client_expiration_seconds",
  157. Help: "Gauge of the lifetime of a certificate. The value is the date the certificate will expire in seconds since January 1, 1970 UTC.",
  158. },
  159. )
  160. prometheus.Register(certificateExpiration)
  161. m, err := certificate.NewManager(&certificate.Config{
  162. ClientFn: clientFn,
  163. Template: &x509.CertificateRequest{
  164. Subject: pkix.Name{
  165. CommonName: fmt.Sprintf("system:node:%s", nodeName),
  166. Organization: []string{"system:nodes"},
  167. },
  168. },
  169. Usages: []certificates.KeyUsage{
  170. // https://tools.ietf.org/html/rfc5280#section-4.2.1.3
  171. //
  172. // DigitalSignature allows the certificate to be used to verify
  173. // digital signatures including signatures used during TLS
  174. // negotiation.
  175. certificates.UsageDigitalSignature,
  176. // KeyEncipherment allows the cert/key pair to be used to encrypt
  177. // keys, including the symmetric keys negotiated during TLS setup
  178. // and used for data transfer..
  179. certificates.UsageKeyEncipherment,
  180. // ClientAuth allows the cert to be used by a TLS client to
  181. // authenticate itself to the TLS server.
  182. certificates.UsageClientAuth,
  183. },
  184. // For backwards compatibility, the kubelet supports the ability to
  185. // provide a higher privileged certificate as initial data that will
  186. // then be rotated immediately. This code path is used by kubeadm on
  187. // the masters.
  188. BootstrapCertificatePEM: bootstrapCertData,
  189. BootstrapKeyPEM: bootstrapKeyData,
  190. CertificateStore: certificateStore,
  191. CertificateExpiration: certificateExpiration,
  192. })
  193. if err != nil {
  194. return nil, fmt.Errorf("failed to initialize client certificate manager: %v", err)
  195. }
  196. return m, nil
  197. }