io.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. /*
  2. Copyright 2014 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 cert
  14. import (
  15. "crypto/x509"
  16. "fmt"
  17. "io/ioutil"
  18. "os"
  19. "path/filepath"
  20. )
  21. // CanReadCertAndKey returns true if the certificate and key files already exists,
  22. // otherwise returns false. If lost one of cert and key, returns error.
  23. func CanReadCertAndKey(certPath, keyPath string) (bool, error) {
  24. certReadable := canReadFile(certPath)
  25. keyReadable := canReadFile(keyPath)
  26. if certReadable == false && keyReadable == false {
  27. return false, nil
  28. }
  29. if certReadable == false {
  30. return false, fmt.Errorf("error reading %s, certificate and key must be supplied as a pair", certPath)
  31. }
  32. if keyReadable == false {
  33. return false, fmt.Errorf("error reading %s, certificate and key must be supplied as a pair", keyPath)
  34. }
  35. return true, nil
  36. }
  37. // If the file represented by path exists and
  38. // readable, returns true otherwise returns false.
  39. func canReadFile(path string) bool {
  40. f, err := os.Open(path)
  41. if err != nil {
  42. return false
  43. }
  44. defer f.Close()
  45. return true
  46. }
  47. // WriteCert writes the pem-encoded certificate data to certPath.
  48. // The certificate file will be created with file mode 0644.
  49. // If the certificate file already exists, it will be overwritten.
  50. // The parent directory of the certPath will be created as needed with file mode 0755.
  51. func WriteCert(certPath string, data []byte) error {
  52. if err := os.MkdirAll(filepath.Dir(certPath), os.FileMode(0755)); err != nil {
  53. return err
  54. }
  55. if err := ioutil.WriteFile(certPath, data, os.FileMode(0644)); err != nil {
  56. return err
  57. }
  58. return nil
  59. }
  60. // WriteKey writes the pem-encoded key data to keyPath.
  61. // The key file will be created with file mode 0600.
  62. // If the key file already exists, it will be overwritten.
  63. // The parent directory of the keyPath will be created as needed with file mode 0755.
  64. func WriteKey(keyPath string, data []byte) error {
  65. if err := os.MkdirAll(filepath.Dir(keyPath), os.FileMode(0755)); err != nil {
  66. return err
  67. }
  68. if err := ioutil.WriteFile(keyPath, data, os.FileMode(0600)); err != nil {
  69. return err
  70. }
  71. return nil
  72. }
  73. // LoadOrGenerateKeyFile looks for a key in the file at the given path. If it
  74. // can't find one, it will generate a new key and store it there.
  75. func LoadOrGenerateKeyFile(keyPath string) (data []byte, wasGenerated bool, err error) {
  76. loadedData, err := ioutil.ReadFile(keyPath)
  77. if err == nil {
  78. return loadedData, false, err
  79. }
  80. if !os.IsNotExist(err) {
  81. return nil, false, fmt.Errorf("error loading key from %s: %v", keyPath, err)
  82. }
  83. generatedData, err := MakeEllipticPrivateKeyPEM()
  84. if err != nil {
  85. return nil, false, fmt.Errorf("error generating key: %v", err)
  86. }
  87. if err := WriteKey(keyPath, generatedData); err != nil {
  88. return nil, false, fmt.Errorf("error writing key to %s: %v", keyPath, err)
  89. }
  90. return generatedData, true, nil
  91. }
  92. // NewPool returns an x509.CertPool containing the certificates in the given PEM-encoded file.
  93. // Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates
  94. func NewPool(filename string) (*x509.CertPool, error) {
  95. certs, err := CertsFromFile(filename)
  96. if err != nil {
  97. return nil, err
  98. }
  99. pool := x509.NewCertPool()
  100. for _, cert := range certs {
  101. pool.AddCert(cert)
  102. }
  103. return pool, nil
  104. }
  105. // CertsFromFile returns the x509.Certificates contained in the given PEM-encoded file.
  106. // Returns an error if the file could not be read, a certificate could not be parsed, or if the file does not contain any certificates
  107. func CertsFromFile(file string) ([]*x509.Certificate, error) {
  108. pemBlock, err := ioutil.ReadFile(file)
  109. if err != nil {
  110. return nil, err
  111. }
  112. certs, err := ParseCertsPEM(pemBlock)
  113. if err != nil {
  114. return nil, fmt.Errorf("error reading %s: %s", file, err)
  115. }
  116. return certs, nil
  117. }
  118. // PrivateKeyFromFile returns the private key in rsa.PrivateKey or ecdsa.PrivateKey format from a given PEM-encoded file.
  119. // Returns an error if the file could not be read or if the private key could not be parsed.
  120. func PrivateKeyFromFile(file string) (interface{}, error) {
  121. pemBlock, err := ioutil.ReadFile(file)
  122. if err != nil {
  123. return nil, err
  124. }
  125. key, err := ParsePrivateKeyPEM(pemBlock)
  126. if err != nil {
  127. return nil, fmt.Errorf("error reading %s: %v", file, err)
  128. }
  129. return key, nil
  130. }