blob: a57bf09d5ebe94fa76c6389a91aa6d6b619242a2 [file] [log] [blame]
sslobodrd046be82019-01-16 10:02:22 -05001/*
2Copyright 2014 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package cert
18
19import (
20 "crypto"
21 "crypto/ecdsa"
22 "crypto/rsa"
23 "crypto/x509"
24 "encoding/pem"
25 "fmt"
26 "io/ioutil"
27 "os"
28 "path/filepath"
29)
30
31// CanReadCertAndKey returns true if the certificate and key files already exists,
32// otherwise returns false. If lost one of cert and key, returns error.
33func CanReadCertAndKey(certPath, keyPath string) (bool, error) {
34 certReadable := canReadFile(certPath)
35 keyReadable := canReadFile(keyPath)
36
37 if certReadable == false && keyReadable == false {
38 return false, nil
39 }
40
41 if certReadable == false {
42 return false, fmt.Errorf("error reading %s, certificate and key must be supplied as a pair", certPath)
43 }
44
45 if keyReadable == false {
46 return false, fmt.Errorf("error reading %s, certificate and key must be supplied as a pair", keyPath)
47 }
48
49 return true, nil
50}
51
52// If the file represented by path exists and
53// readable, returns true otherwise returns false.
54func canReadFile(path string) bool {
55 f, err := os.Open(path)
56 if err != nil {
57 return false
58 }
59
60 defer f.Close()
61
62 return true
63}
64
65// WriteCert writes the pem-encoded certificate data to certPath.
66// The certificate file will be created with file mode 0644.
67// If the certificate file already exists, it will be overwritten.
68// The parent directory of the certPath will be created as needed with file mode 0755.
69func WriteCert(certPath string, data []byte) error {
70 if err := os.MkdirAll(filepath.Dir(certPath), os.FileMode(0755)); err != nil {
71 return err
72 }
73 return ioutil.WriteFile(certPath, data, os.FileMode(0644))
74}
75
76// WriteKey writes the pem-encoded key data to keyPath.
77// The key file will be created with file mode 0600.
78// If the key file already exists, it will be overwritten.
79// The parent directory of the keyPath will be created as needed with file mode 0755.
80func WriteKey(keyPath string, data []byte) error {
81 if err := os.MkdirAll(filepath.Dir(keyPath), os.FileMode(0755)); err != nil {
82 return err
83 }
84 return ioutil.WriteFile(keyPath, data, os.FileMode(0600))
85}
86
87// LoadOrGenerateKeyFile looks for a key in the file at the given path. If it
88// can't find one, it will generate a new key and store it there.
89func LoadOrGenerateKeyFile(keyPath string) (data []byte, wasGenerated bool, err error) {
90 loadedData, err := ioutil.ReadFile(keyPath)
91 // Call verifyKeyData to ensure the file wasn't empty/corrupt.
92 if err == nil && verifyKeyData(loadedData) {
93 return loadedData, false, err
94 }
95 if !os.IsNotExist(err) {
96 return nil, false, fmt.Errorf("error loading key from %s: %v", keyPath, err)
97 }
98
99 generatedData, err := MakeEllipticPrivateKeyPEM()
100 if err != nil {
101 return nil, false, fmt.Errorf("error generating key: %v", err)
102 }
103 if err := WriteKey(keyPath, generatedData); err != nil {
104 return nil, false, fmt.Errorf("error writing key to %s: %v", keyPath, err)
105 }
106 return generatedData, true, nil
107}
108
109// MarshalPrivateKeyToPEM converts a known private key type of RSA or ECDSA to
110// a PEM encoded block or returns an error.
111func MarshalPrivateKeyToPEM(privateKey crypto.PrivateKey) ([]byte, error) {
112 switch t := privateKey.(type) {
113 case *ecdsa.PrivateKey:
114 derBytes, err := x509.MarshalECPrivateKey(t)
115 if err != nil {
116 return nil, err
117 }
118 privateKeyPemBlock := &pem.Block{
119 Type: ECPrivateKeyBlockType,
120 Bytes: derBytes,
121 }
122 return pem.EncodeToMemory(privateKeyPemBlock), nil
123 case *rsa.PrivateKey:
124 return EncodePrivateKeyPEM(t), nil
125 default:
126 return nil, fmt.Errorf("private key is not a recognized type: %T", privateKey)
127 }
128}
129
130// NewPool returns an x509.CertPool containing the certificates in the given PEM-encoded file.
131// 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
132func NewPool(filename string) (*x509.CertPool, error) {
133 certs, err := CertsFromFile(filename)
134 if err != nil {
135 return nil, err
136 }
137 pool := x509.NewCertPool()
138 for _, cert := range certs {
139 pool.AddCert(cert)
140 }
141 return pool, nil
142}
143
144// CertsFromFile returns the x509.Certificates contained in the given PEM-encoded file.
145// 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
146func CertsFromFile(file string) ([]*x509.Certificate, error) {
147 pemBlock, err := ioutil.ReadFile(file)
148 if err != nil {
149 return nil, err
150 }
151 certs, err := ParseCertsPEM(pemBlock)
152 if err != nil {
153 return nil, fmt.Errorf("error reading %s: %s", file, err)
154 }
155 return certs, nil
156}
157
158// PrivateKeyFromFile returns the private key in rsa.PrivateKey or ecdsa.PrivateKey format from a given PEM-encoded file.
159// Returns an error if the file could not be read or if the private key could not be parsed.
160func PrivateKeyFromFile(file string) (interface{}, error) {
161 data, err := ioutil.ReadFile(file)
162 if err != nil {
163 return nil, err
164 }
165 key, err := ParsePrivateKeyPEM(data)
166 if err != nil {
167 return nil, fmt.Errorf("error reading private key file %s: %v", file, err)
168 }
169 return key, nil
170}
171
172// PublicKeysFromFile returns the public keys in rsa.PublicKey or ecdsa.PublicKey format from a given PEM-encoded file.
173// Reads public keys from both public and private key files.
174func PublicKeysFromFile(file string) ([]interface{}, error) {
175 data, err := ioutil.ReadFile(file)
176 if err != nil {
177 return nil, err
178 }
179 keys, err := ParsePublicKeysPEM(data)
180 if err != nil {
181 return nil, fmt.Errorf("error reading public key file %s: %v", file, err)
182 }
183 return keys, nil
184}
185
186// verifyKeyData returns true if the provided data appears to be a valid private key.
187func verifyKeyData(data []byte) bool {
188 if len(data) == 0 {
189 return false
190 }
191 _, err := ParsePrivateKeyPEM(data)
192 return err == nil
193}