pki_helpers.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. /*
  2. Copyright 2016 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 pkiutil
  14. import (
  15. "crypto"
  16. "crypto/ecdsa"
  17. "crypto/elliptic"
  18. cryptorand "crypto/rand"
  19. "crypto/rsa"
  20. "crypto/x509"
  21. "crypto/x509/pkix"
  22. "encoding/pem"
  23. "fmt"
  24. "io/ioutil"
  25. "math"
  26. "math/big"
  27. "net"
  28. "os"
  29. "path/filepath"
  30. "time"
  31. "github.com/pkg/errors"
  32. "k8s.io/apimachinery/pkg/util/validation"
  33. certutil "k8s.io/client-go/util/cert"
  34. "k8s.io/client-go/util/keyutil"
  35. kubeadmapi "k8s.io/kubernetes/cmd/kubeadm/app/apis/kubeadm"
  36. kubeadmconstants "k8s.io/kubernetes/cmd/kubeadm/app/constants"
  37. "k8s.io/kubernetes/cmd/kubeadm/app/features"
  38. kubeadmutil "k8s.io/kubernetes/cmd/kubeadm/app/util"
  39. )
  40. const (
  41. // PrivateKeyBlockType is a possible value for pem.Block.Type.
  42. PrivateKeyBlockType = "PRIVATE KEY"
  43. // PublicKeyBlockType is a possible value for pem.Block.Type.
  44. PublicKeyBlockType = "PUBLIC KEY"
  45. // CertificateBlockType is a possible value for pem.Block.Type.
  46. CertificateBlockType = "CERTIFICATE"
  47. // RSAPrivateKeyBlockType is a possible value for pem.Block.Type.
  48. RSAPrivateKeyBlockType = "RSA PRIVATE KEY"
  49. rsaKeySize = 2048
  50. )
  51. // CertConfig is a wrapper around certutil.Config extending it with PublicKeyAlgorithm.
  52. type CertConfig struct {
  53. certutil.Config
  54. PublicKeyAlgorithm x509.PublicKeyAlgorithm
  55. }
  56. // NewCertificateAuthority creates new certificate and private key for the certificate authority
  57. func NewCertificateAuthority(config *CertConfig) (*x509.Certificate, crypto.Signer, error) {
  58. key, err := NewPrivateKey(config.PublicKeyAlgorithm)
  59. if err != nil {
  60. return nil, nil, errors.Wrap(err, "unable to create private key while generating CA certificate")
  61. }
  62. cert, err := certutil.NewSelfSignedCACert(config.Config, key)
  63. if err != nil {
  64. return nil, nil, errors.Wrap(err, "unable to create self-signed CA certificate")
  65. }
  66. return cert, key, nil
  67. }
  68. // NewCertAndKey creates new certificate and key by passing the certificate authority certificate and key
  69. func NewCertAndKey(caCert *x509.Certificate, caKey crypto.Signer, config *CertConfig) (*x509.Certificate, crypto.Signer, error) {
  70. key, err := NewPrivateKey(config.PublicKeyAlgorithm)
  71. if err != nil {
  72. return nil, nil, errors.Wrap(err, "unable to create private key")
  73. }
  74. cert, err := NewSignedCert(config, key, caCert, caKey)
  75. if err != nil {
  76. return nil, nil, errors.Wrap(err, "unable to sign certificate")
  77. }
  78. return cert, key, nil
  79. }
  80. // NewCSRAndKey generates a new key and CSR and that could be signed to create the given certificate
  81. func NewCSRAndKey(config *CertConfig) (*x509.CertificateRequest, crypto.Signer, error) {
  82. key, err := NewPrivateKey(config.PublicKeyAlgorithm)
  83. if err != nil {
  84. return nil, nil, errors.Wrap(err, "unable to create private key")
  85. }
  86. csr, err := NewCSR(*config, key)
  87. if err != nil {
  88. return nil, nil, errors.Wrap(err, "unable to generate CSR")
  89. }
  90. return csr, key, nil
  91. }
  92. // HasServerAuth returns true if the given certificate is a ServerAuth
  93. func HasServerAuth(cert *x509.Certificate) bool {
  94. for i := range cert.ExtKeyUsage {
  95. if cert.ExtKeyUsage[i] == x509.ExtKeyUsageServerAuth {
  96. return true
  97. }
  98. }
  99. return false
  100. }
  101. // WriteCertAndKey stores certificate and key at the specified location
  102. func WriteCertAndKey(pkiPath string, name string, cert *x509.Certificate, key crypto.Signer) error {
  103. if err := WriteKey(pkiPath, name, key); err != nil {
  104. return errors.Wrap(err, "couldn't write key")
  105. }
  106. return WriteCert(pkiPath, name, cert)
  107. }
  108. // WriteCert stores the given certificate at the given location
  109. func WriteCert(pkiPath, name string, cert *x509.Certificate) error {
  110. if cert == nil {
  111. return errors.New("certificate cannot be nil when writing to file")
  112. }
  113. certificatePath := pathForCert(pkiPath, name)
  114. if err := certutil.WriteCert(certificatePath, EncodeCertPEM(cert)); err != nil {
  115. return errors.Wrapf(err, "unable to write certificate to file %s", certificatePath)
  116. }
  117. return nil
  118. }
  119. // WriteKey stores the given key at the given location
  120. func WriteKey(pkiPath, name string, key crypto.Signer) error {
  121. if key == nil {
  122. return errors.New("private key cannot be nil when writing to file")
  123. }
  124. privateKeyPath := pathForKey(pkiPath, name)
  125. encoded, err := keyutil.MarshalPrivateKeyToPEM(key)
  126. if err != nil {
  127. return errors.Wrapf(err, "unable to marshal private key to PEM")
  128. }
  129. if err := keyutil.WriteKey(privateKeyPath, encoded); err != nil {
  130. return errors.Wrapf(err, "unable to write private key to file %s", privateKeyPath)
  131. }
  132. return nil
  133. }
  134. // WriteCSR writes the pem-encoded CSR data to csrPath.
  135. // The CSR file will be created with file mode 0600.
  136. // If the CSR file already exists, it will be overwritten.
  137. // The parent directory of the csrPath will be created as needed with file mode 0700.
  138. func WriteCSR(csrDir, name string, csr *x509.CertificateRequest) error {
  139. if csr == nil {
  140. return errors.New("certificate request cannot be nil when writing to file")
  141. }
  142. csrPath := pathForCSR(csrDir, name)
  143. if err := os.MkdirAll(filepath.Dir(csrPath), os.FileMode(0700)); err != nil {
  144. return errors.Wrapf(err, "failed to make directory %s", filepath.Dir(csrPath))
  145. }
  146. if err := ioutil.WriteFile(csrPath, EncodeCSRPEM(csr), os.FileMode(0600)); err != nil {
  147. return errors.Wrapf(err, "unable to write CSR to file %s", csrPath)
  148. }
  149. return nil
  150. }
  151. // WritePublicKey stores the given public key at the given location
  152. func WritePublicKey(pkiPath, name string, key crypto.PublicKey) error {
  153. if key == nil {
  154. return errors.New("public key cannot be nil when writing to file")
  155. }
  156. publicKeyBytes, err := EncodePublicKeyPEM(key)
  157. if err != nil {
  158. return err
  159. }
  160. publicKeyPath := pathForPublicKey(pkiPath, name)
  161. if err := keyutil.WriteKey(publicKeyPath, publicKeyBytes); err != nil {
  162. return errors.Wrapf(err, "unable to write public key to file %s", publicKeyPath)
  163. }
  164. return nil
  165. }
  166. // CertOrKeyExist returns a boolean whether the cert or the key exists
  167. func CertOrKeyExist(pkiPath, name string) bool {
  168. certificatePath, privateKeyPath := PathsForCertAndKey(pkiPath, name)
  169. _, certErr := os.Stat(certificatePath)
  170. _, keyErr := os.Stat(privateKeyPath)
  171. if os.IsNotExist(certErr) && os.IsNotExist(keyErr) {
  172. // The cert and the key do not exist
  173. return false
  174. }
  175. // Both files exist or one of them
  176. return true
  177. }
  178. // CSROrKeyExist returns true if one of the CSR or key exists
  179. func CSROrKeyExist(csrDir, name string) bool {
  180. csrPath := pathForCSR(csrDir, name)
  181. keyPath := pathForKey(csrDir, name)
  182. _, csrErr := os.Stat(csrPath)
  183. _, keyErr := os.Stat(keyPath)
  184. return !(os.IsNotExist(csrErr) && os.IsNotExist(keyErr))
  185. }
  186. // TryLoadCertAndKeyFromDisk tries to load a cert and a key from the disk and validates that they are valid
  187. func TryLoadCertAndKeyFromDisk(pkiPath, name string) (*x509.Certificate, crypto.Signer, error) {
  188. cert, err := TryLoadCertFromDisk(pkiPath, name)
  189. if err != nil {
  190. return nil, nil, errors.Wrap(err, "failed to load certificate")
  191. }
  192. key, err := TryLoadKeyFromDisk(pkiPath, name)
  193. if err != nil {
  194. return nil, nil, errors.Wrap(err, "failed to load key")
  195. }
  196. return cert, key, nil
  197. }
  198. // TryLoadCertFromDisk tries to load the cert from the disk and validates that it is valid
  199. func TryLoadCertFromDisk(pkiPath, name string) (*x509.Certificate, error) {
  200. certificatePath := pathForCert(pkiPath, name)
  201. certs, err := certutil.CertsFromFile(certificatePath)
  202. if err != nil {
  203. return nil, errors.Wrapf(err, "couldn't load the certificate file %s", certificatePath)
  204. }
  205. // We are only putting one certificate in the certificate pem file, so it's safe to just pick the first one
  206. // TODO: Support multiple certs here in order to be able to rotate certs
  207. cert := certs[0]
  208. // Check so that the certificate is valid now
  209. now := time.Now()
  210. if now.Before(cert.NotBefore) {
  211. return nil, errors.New("the certificate is not valid yet")
  212. }
  213. if now.After(cert.NotAfter) {
  214. return nil, errors.New("the certificate has expired")
  215. }
  216. return cert, nil
  217. }
  218. // TryLoadKeyFromDisk tries to load the key from the disk and validates that it is valid
  219. func TryLoadKeyFromDisk(pkiPath, name string) (crypto.Signer, error) {
  220. privateKeyPath := pathForKey(pkiPath, name)
  221. // Parse the private key from a file
  222. privKey, err := keyutil.PrivateKeyFromFile(privateKeyPath)
  223. if err != nil {
  224. return nil, errors.Wrapf(err, "couldn't load the private key file %s", privateKeyPath)
  225. }
  226. // Allow RSA and ECDSA formats only
  227. var key crypto.Signer
  228. switch k := privKey.(type) {
  229. case *rsa.PrivateKey:
  230. key = k
  231. case *ecdsa.PrivateKey:
  232. key = k
  233. default:
  234. return nil, errors.Errorf("the private key file %s is neither in RSA nor ECDSA format", privateKeyPath)
  235. }
  236. return key, nil
  237. }
  238. // TryLoadCSRAndKeyFromDisk tries to load the CSR and key from the disk
  239. func TryLoadCSRAndKeyFromDisk(pkiPath, name string) (*x509.CertificateRequest, crypto.Signer, error) {
  240. csrPath := pathForCSR(pkiPath, name)
  241. csr, err := CertificateRequestFromFile(csrPath)
  242. if err != nil {
  243. return nil, nil, errors.Wrapf(err, "couldn't load the certificate request %s", csrPath)
  244. }
  245. key, err := TryLoadKeyFromDisk(pkiPath, name)
  246. if err != nil {
  247. return nil, nil, errors.Wrap(err, "couldn't load key file")
  248. }
  249. return csr, key, nil
  250. }
  251. // TryLoadPrivatePublicKeyFromDisk tries to load the key from the disk and validates that it is valid
  252. func TryLoadPrivatePublicKeyFromDisk(pkiPath, name string) (*rsa.PrivateKey, *rsa.PublicKey, error) {
  253. privateKeyPath := pathForKey(pkiPath, name)
  254. // Parse the private key from a file
  255. privKey, err := keyutil.PrivateKeyFromFile(privateKeyPath)
  256. if err != nil {
  257. return nil, nil, errors.Wrapf(err, "couldn't load the private key file %s", privateKeyPath)
  258. }
  259. publicKeyPath := pathForPublicKey(pkiPath, name)
  260. // Parse the public key from a file
  261. pubKeys, err := keyutil.PublicKeysFromFile(publicKeyPath)
  262. if err != nil {
  263. return nil, nil, errors.Wrapf(err, "couldn't load the public key file %s", publicKeyPath)
  264. }
  265. // Allow RSA format only
  266. k, ok := privKey.(*rsa.PrivateKey)
  267. if !ok {
  268. return nil, nil, errors.Errorf("the private key file %s isn't in RSA format", privateKeyPath)
  269. }
  270. p := pubKeys[0].(*rsa.PublicKey)
  271. return k, p, nil
  272. }
  273. // PathsForCertAndKey returns the paths for the certificate and key given the path and basename.
  274. func PathsForCertAndKey(pkiPath, name string) (string, string) {
  275. return pathForCert(pkiPath, name), pathForKey(pkiPath, name)
  276. }
  277. func pathForCert(pkiPath, name string) string {
  278. return filepath.Join(pkiPath, fmt.Sprintf("%s.crt", name))
  279. }
  280. func pathForKey(pkiPath, name string) string {
  281. return filepath.Join(pkiPath, fmt.Sprintf("%s.key", name))
  282. }
  283. func pathForPublicKey(pkiPath, name string) string {
  284. return filepath.Join(pkiPath, fmt.Sprintf("%s.pub", name))
  285. }
  286. func pathForCSR(pkiPath, name string) string {
  287. return filepath.Join(pkiPath, fmt.Sprintf("%s.csr", name))
  288. }
  289. // GetAPIServerAltNames builds an AltNames object for to be used when generating apiserver certificate
  290. func GetAPIServerAltNames(cfg *kubeadmapi.InitConfiguration) (*certutil.AltNames, error) {
  291. // advertise address
  292. advertiseAddress := net.ParseIP(cfg.LocalAPIEndpoint.AdvertiseAddress)
  293. if advertiseAddress == nil {
  294. return nil, errors.Errorf("error parsing LocalAPIEndpoint AdvertiseAddress %v: is not a valid textual representation of an IP address",
  295. cfg.LocalAPIEndpoint.AdvertiseAddress)
  296. }
  297. internalAPIServerVirtualIP, err := kubeadmconstants.GetAPIServerVirtualIP(cfg.Networking.ServiceSubnet, features.Enabled(cfg.FeatureGates, features.IPv6DualStack))
  298. if err != nil {
  299. return nil, errors.Wrapf(err, "unable to get first IP address from the given CIDR: %v", cfg.Networking.ServiceSubnet)
  300. }
  301. // create AltNames with defaults DNSNames/IPs
  302. altNames := &certutil.AltNames{
  303. DNSNames: []string{
  304. cfg.NodeRegistration.Name,
  305. "kubernetes",
  306. "kubernetes.default",
  307. "kubernetes.default.svc",
  308. fmt.Sprintf("kubernetes.default.svc.%s", cfg.Networking.DNSDomain),
  309. },
  310. IPs: []net.IP{
  311. internalAPIServerVirtualIP,
  312. advertiseAddress,
  313. },
  314. }
  315. // add cluster controlPlaneEndpoint if present (dns or ip)
  316. if len(cfg.ControlPlaneEndpoint) > 0 {
  317. if host, _, err := kubeadmutil.ParseHostPort(cfg.ControlPlaneEndpoint); err == nil {
  318. if ip := net.ParseIP(host); ip != nil {
  319. altNames.IPs = append(altNames.IPs, ip)
  320. } else {
  321. altNames.DNSNames = append(altNames.DNSNames, host)
  322. }
  323. } else {
  324. return nil, errors.Wrapf(err, "error parsing cluster controlPlaneEndpoint %q", cfg.ControlPlaneEndpoint)
  325. }
  326. }
  327. appendSANsToAltNames(altNames, cfg.APIServer.CertSANs, kubeadmconstants.APIServerCertName)
  328. return altNames, nil
  329. }
  330. // GetEtcdAltNames builds an AltNames object for generating the etcd server certificate.
  331. // `advertise address` and localhost are included in the SAN since this is the interfaces the etcd static pod listens on.
  332. // The user can override the listen address with `Etcd.ExtraArgs` and add SANs with `Etcd.ServerCertSANs`.
  333. func GetEtcdAltNames(cfg *kubeadmapi.InitConfiguration) (*certutil.AltNames, error) {
  334. return getAltNames(cfg, kubeadmconstants.EtcdServerCertName)
  335. }
  336. // GetEtcdPeerAltNames builds an AltNames object for generating the etcd peer certificate.
  337. // Hostname and `API.AdvertiseAddress` are included if the user chooses to promote the single node etcd cluster into a multi-node one (stacked etcd).
  338. // The user can override the listen address with `Etcd.ExtraArgs` and add SANs with `Etcd.PeerCertSANs`.
  339. func GetEtcdPeerAltNames(cfg *kubeadmapi.InitConfiguration) (*certutil.AltNames, error) {
  340. return getAltNames(cfg, kubeadmconstants.EtcdPeerCertName)
  341. }
  342. // getAltNames builds an AltNames object with the cfg and certName.
  343. func getAltNames(cfg *kubeadmapi.InitConfiguration, certName string) (*certutil.AltNames, error) {
  344. // advertise address
  345. advertiseAddress := net.ParseIP(cfg.LocalAPIEndpoint.AdvertiseAddress)
  346. if advertiseAddress == nil {
  347. return nil, errors.Errorf("error parsing LocalAPIEndpoint AdvertiseAddress %v: is not a valid textual representation of an IP address",
  348. cfg.LocalAPIEndpoint.AdvertiseAddress)
  349. }
  350. // create AltNames with defaults DNSNames/IPs
  351. altNames := &certutil.AltNames{
  352. DNSNames: []string{cfg.NodeRegistration.Name, "localhost"},
  353. IPs: []net.IP{advertiseAddress, net.IPv4(127, 0, 0, 1), net.IPv6loopback},
  354. }
  355. if cfg.Etcd.Local != nil {
  356. if certName == kubeadmconstants.EtcdServerCertName {
  357. appendSANsToAltNames(altNames, cfg.Etcd.Local.ServerCertSANs, kubeadmconstants.EtcdServerCertName)
  358. } else if certName == kubeadmconstants.EtcdPeerCertName {
  359. appendSANsToAltNames(altNames, cfg.Etcd.Local.PeerCertSANs, kubeadmconstants.EtcdPeerCertName)
  360. }
  361. }
  362. return altNames, nil
  363. }
  364. // appendSANsToAltNames parses SANs from as list of strings and adds them to altNames for use on a specific cert
  365. // altNames is passed in with a pointer, and the struct is modified
  366. // valid IP address strings are parsed and added to altNames.IPs as net.IP's
  367. // RFC-1123 compliant DNS strings are added to altNames.DNSNames as strings
  368. // RFC-1123 compliant wildcard DNS strings are added to altNames.DNSNames as strings
  369. // certNames is used to print user facing warnings and should be the name of the cert the altNames will be used for
  370. func appendSANsToAltNames(altNames *certutil.AltNames, SANs []string, certName string) {
  371. for _, altname := range SANs {
  372. if ip := net.ParseIP(altname); ip != nil {
  373. altNames.IPs = append(altNames.IPs, ip)
  374. } else if len(validation.IsDNS1123Subdomain(altname)) == 0 {
  375. altNames.DNSNames = append(altNames.DNSNames, altname)
  376. } else if len(validation.IsWildcardDNS1123Subdomain(altname)) == 0 {
  377. altNames.DNSNames = append(altNames.DNSNames, altname)
  378. } else {
  379. fmt.Printf(
  380. "[certificates] WARNING: '%s' was not added to the '%s' SAN, because it is not a valid IP or RFC-1123 compliant DNS entry\n",
  381. altname,
  382. certName,
  383. )
  384. }
  385. }
  386. }
  387. // EncodeCSRPEM returns PEM-encoded CSR data
  388. func EncodeCSRPEM(csr *x509.CertificateRequest) []byte {
  389. block := pem.Block{
  390. Type: certutil.CertificateRequestBlockType,
  391. Bytes: csr.Raw,
  392. }
  393. return pem.EncodeToMemory(&block)
  394. }
  395. func parseCSRPEM(pemCSR []byte) (*x509.CertificateRequest, error) {
  396. block, _ := pem.Decode(pemCSR)
  397. if block == nil {
  398. return nil, errors.New("data doesn't contain a valid certificate request")
  399. }
  400. if block.Type != certutil.CertificateRequestBlockType {
  401. return nil, errors.Errorf("expected block type %q, but PEM had type %q", certutil.CertificateRequestBlockType, block.Type)
  402. }
  403. return x509.ParseCertificateRequest(block.Bytes)
  404. }
  405. // CertificateRequestFromFile returns the CertificateRequest from a given PEM-encoded file.
  406. // Returns an error if the file could not be read or if the CSR could not be parsed.
  407. func CertificateRequestFromFile(file string) (*x509.CertificateRequest, error) {
  408. pemBlock, err := ioutil.ReadFile(file)
  409. if err != nil {
  410. return nil, errors.Wrap(err, "failed to read file")
  411. }
  412. csr, err := parseCSRPEM(pemBlock)
  413. if err != nil {
  414. return nil, errors.Wrapf(err, "error reading certificate request file %s", file)
  415. }
  416. return csr, nil
  417. }
  418. // NewCSR creates a new CSR
  419. func NewCSR(cfg CertConfig, key crypto.Signer) (*x509.CertificateRequest, error) {
  420. template := &x509.CertificateRequest{
  421. Subject: pkix.Name{
  422. CommonName: cfg.CommonName,
  423. Organization: cfg.Organization,
  424. },
  425. DNSNames: cfg.AltNames.DNSNames,
  426. IPAddresses: cfg.AltNames.IPs,
  427. }
  428. csrBytes, err := x509.CreateCertificateRequest(cryptorand.Reader, template, key)
  429. if err != nil {
  430. return nil, errors.Wrap(err, "failed to create a CSR")
  431. }
  432. return x509.ParseCertificateRequest(csrBytes)
  433. }
  434. // EncodeCertPEM returns PEM-endcoded certificate data
  435. func EncodeCertPEM(cert *x509.Certificate) []byte {
  436. block := pem.Block{
  437. Type: CertificateBlockType,
  438. Bytes: cert.Raw,
  439. }
  440. return pem.EncodeToMemory(&block)
  441. }
  442. // EncodePublicKeyPEM returns PEM-encoded public data
  443. func EncodePublicKeyPEM(key crypto.PublicKey) ([]byte, error) {
  444. der, err := x509.MarshalPKIXPublicKey(key)
  445. if err != nil {
  446. return []byte{}, err
  447. }
  448. block := pem.Block{
  449. Type: PublicKeyBlockType,
  450. Bytes: der,
  451. }
  452. return pem.EncodeToMemory(&block), nil
  453. }
  454. // NewPrivateKey creates an RSA private key
  455. func NewPrivateKey(keyType x509.PublicKeyAlgorithm) (crypto.Signer, error) {
  456. if keyType == x509.ECDSA {
  457. return ecdsa.GenerateKey(elliptic.P256(), cryptorand.Reader)
  458. }
  459. return rsa.GenerateKey(cryptorand.Reader, rsaKeySize)
  460. }
  461. // NewSignedCert creates a signed certificate using the given CA certificate and key
  462. func NewSignedCert(cfg *CertConfig, key crypto.Signer, caCert *x509.Certificate, caKey crypto.Signer) (*x509.Certificate, error) {
  463. serial, err := cryptorand.Int(cryptorand.Reader, new(big.Int).SetInt64(math.MaxInt64))
  464. if err != nil {
  465. return nil, err
  466. }
  467. if len(cfg.CommonName) == 0 {
  468. return nil, errors.New("must specify a CommonName")
  469. }
  470. if len(cfg.Usages) == 0 {
  471. return nil, errors.New("must specify at least one ExtKeyUsage")
  472. }
  473. certTmpl := x509.Certificate{
  474. Subject: pkix.Name{
  475. CommonName: cfg.CommonName,
  476. Organization: cfg.Organization,
  477. },
  478. DNSNames: cfg.AltNames.DNSNames,
  479. IPAddresses: cfg.AltNames.IPs,
  480. SerialNumber: serial,
  481. NotBefore: caCert.NotBefore,
  482. NotAfter: time.Now().Add(kubeadmconstants.CertificateValidity).UTC(),
  483. KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
  484. ExtKeyUsage: cfg.Usages,
  485. }
  486. certDERBytes, err := x509.CreateCertificate(cryptorand.Reader, &certTmpl, caCert, key.Public(), caKey)
  487. if err != nil {
  488. return nil, err
  489. }
  490. return x509.ParseCertificate(certDERBytes)
  491. }