forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parsegen.go
203 lines (176 loc) · 6.34 KB
/
parsegen.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
/*
Copyright 2017 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package tlsca
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"math/big"
"time"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/trace"
)
// ClusterName returns cluster name from organization
func ClusterName(subject pkix.Name) (string, error) {
if len(subject.Organization) == 0 {
return "", trace.BadParameter("missing subject organization")
}
return subject.Organization[0], nil
}
// GenerateRSAPrivateKeyPEM generates new RSA private key and returns PEM encoded bytes
func GenerateRSAPrivateKeyPEM() ([]byte, error) {
priv, err := rsa.GenerateKey(rand.Reader, defaults.RSABits)
if err != nil {
return nil, trace.Wrap(err)
}
return pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}), nil
}
// GenerateSelfSignedCA generates self-signed certificate authority used for internal inter-node communications
func GenerateSelfSignedCAWithPrivateKey(priv *rsa.PrivateKey, entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error) {
notBefore := time.Now()
notAfter := notBefore.Add(ttl)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, nil, trace.Wrap(err)
}
// this is important, otherwise go will accept certificate authorities
// signed by the same private key and having the same subject (happens in tests)
entity.SerialNumber = serialNumber.String()
template := x509.Certificate{
SerialNumber: serialNumber,
Issuer: entity,
Subject: entity,
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
IsCA: true,
DNSNames: dnsNames,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return nil, nil, trace.Wrap(err)
}
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)})
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
return keyPEM, certPEM, nil
}
// GenerateSelfSignedCA generates self-signed certificate authority used for internal inter-node communications
func GenerateSelfSignedCA(entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error) {
priv, err := rsa.GenerateKey(rand.Reader, defaults.RSABits)
if err != nil {
return nil, nil, trace.Wrap(err)
}
return GenerateSelfSignedCAWithPrivateKey(priv, entity, dnsNames, ttl)
}
// ParseCertificateRequestPEM parses PEM-encoded certificate signing request
func ParseCertificateRequestPEM(bytes []byte) (*x509.CertificateRequest, error) {
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
csr, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
return nil, trace.BadParameter(err.Error())
}
return csr, nil
}
// ParseCertificatePEM parses PEM-encoded certificate
func ParseCertificatePEM(bytes []byte) (*x509.Certificate, error) {
if len(bytes) == 0 {
return nil, trace.BadParameter("missing PEM encoded block")
}
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, trace.BadParameter(err.Error())
}
return cert, nil
}
// ParsePrivateKeyPEM parses PEM-encoded private key
func ParsePrivateKeyPEM(bytes []byte) (crypto.Signer, error) {
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
return ParsePrivateKeyDER(block.Bytes)
}
// ParsePrivateKeyDER parses unencrypted DER-encoded private key
func ParsePrivateKeyDER(der []byte) (crypto.Signer, error) {
generalKey, err := x509.ParsePKCS8PrivateKey(der)
if err != nil {
generalKey, err = x509.ParsePKCS1PrivateKey(der)
if err != nil {
generalKey, err = x509.ParseECPrivateKey(der)
if err != nil {
return nil, trace.BadParameter("failed parsing private key")
}
}
}
switch generalKey.(type) {
case *rsa.PrivateKey:
return generalKey.(*rsa.PrivateKey), nil
case *ecdsa.PrivateKey:
return generalKey.(*ecdsa.PrivateKey), nil
}
return nil, trace.BadParameter("unsupported private key type")
}
// ParsePublicKeyPEM parses public key PEM
func ParsePublicKeyPEM(bytes []byte) (interface{}, error) {
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
return ParsePublicKeyDER(block.Bytes)
}
// ParsePublicKeyDER parses unencrypted DER-encoded publice key
func ParsePublicKeyDER(der []byte) (crypto.PublicKey, error) {
generalKey, err := x509.ParsePKIXPublicKey(der)
if err != nil {
return nil, trace.Wrap(err)
}
return generalKey, nil
}
// MarshalPublicKeyFromPrivateKeyPEM extracts public key from private key
// and returns PEM marshalled key
func MarshalPublicKeyFromPrivateKeyPEM(privateKey crypto.PrivateKey) ([]byte, error) {
rsaPrivateKey, ok := privateKey.(*rsa.PrivateKey)
if !ok {
return nil, trace.BadParameter("expected RSA key")
}
rsaPublicKey := rsaPrivateKey.Public()
derBytes, err := x509.MarshalPKIXPublicKey(rsaPublicKey)
if err != nil {
return nil, trace.Wrap(err)
}
return pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: derBytes}), nil
}
// MarshalCertificatePEM takes a *x509.Certificate and returns the PEM
// encoded bytes.
func MarshalCertificatePEM(cert *x509.Certificate) ([]byte, error) {
var buf bytes.Buffer
err := pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw})
if err != nil {
return nil, trace.Wrap(err)
}
return buf.Bytes(), nil
}