-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
ca_export.go
339 lines (307 loc) · 11 KB
/
ca_export.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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
/*
* Teleport
* Copyright (C) 2023 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package client
import (
"context"
"encoding/pem"
"errors"
"strings"
"time"
"github.com/gravitational/trace"
apidefaults "github.com/gravitational/teleport/api/defaults"
"github.com/gravitational/teleport/api/mfa"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/sshutils"
)
// ExportAuthoritiesRequest has the required fields to create an export authorities request.
//
// An empty AuthType exports all types.
//
// When exporting private keys, you can set ExportAuthorityFingerprint to filter the authority.
// Fingerprint must be the SHA256 of the Authority's public key.
//
// You can export using the old 1.0 format where host and user
// certificate authorities were exported in the known_hosts format.
// To do so, set UseCompatVersion to true.
type ExportAuthoritiesRequest struct {
AuthType string
ExportAuthorityFingerprint string
UseCompatVersion bool
}
// ExportAuthorities returns the list of authorities in OpenSSH compatible formats as a string.
// If the ExportAuthoritiesRequest.AuthType is present only prints keys for CAs of this type,
// otherwise returns host and user SSH keys.
//
// Exporting using "tls*", "database", "windows" AuthType:
// Returns the certificate authority public key to be used by systems that rely on TLS.
// The format can be PEM or DER depending on the target.
//
// Exporting using "user" AuthType:
// Returns the certificate authority public key exported as a single
// line that can be placed in ~/.ssh/authorized_keys file. The format adheres to the
// man sshd (8) authorized_keys format, a space-separated list of: options, keytype,
// base64-encoded key, comment.
// For example:
// > cert-authority AAA... type=user&clustername=cluster-a
// URL encoding is used to pass the CA type and cluster name into the comment field.
//
// Exporting using "host" AuthType:
// Returns the certificate authority public key exported as a single line
// that can be placed in ~/.ssh/known_hosts. The format adheres to the man sshd (8)
// known_hosts format, a space-separated list of: marker, hosts, key, and comment.
// For example:
// > @cert-authority *.cluster-a ssh-rsa AAA... type=host
// URL encoding is used to pass the CA type and allowed logins into the comment field.
func ExportAuthorities(ctx context.Context, client auth.ClientI, req ExportAuthoritiesRequest) (string, error) {
return exportAuth(ctx, client, req, false /* exportSecrets */)
}
// ExportAuthoritiesSecrets exports the Authority Certificate secrets (private keys).
// See ExportAuthorities for more information.
func ExportAuthoritiesSecrets(ctx context.Context, client auth.ClientI, req ExportAuthoritiesRequest) (string, error) {
return exportAuth(ctx, client, req, true /* exportSecrets */)
}
func exportAuth(ctx context.Context, client auth.ClientI, req ExportAuthoritiesRequest, exportSecrets bool) (string, error) {
var typesToExport []types.CertAuthType
if exportSecrets {
mfaResponse, err := mfa.PerformAdminActionMFACeremony(ctx, client.PerformMFACeremony, true /*allowReuse*/)
if err == nil {
ctx = mfa.ContextWithMFAResponse(ctx, mfaResponse)
} else if !errors.Is(err, &mfa.ErrMFANotRequired) && !errors.Is(err, &mfa.ErrMFANotSupported) {
return "", trace.Wrap(err)
}
}
// this means to export TLS authority
switch req.AuthType {
// "tls" is supported for backwards compatibility.
// "tls-host" and "tls-user" were added later to allow export of the user
// TLS CA.
case "tls", "tls-host":
req := exportTLSAuthorityRequest{
AuthType: types.HostCA,
UnpackPEM: false,
ExportPrivateKeys: exportSecrets,
}
return exportTLSAuthority(ctx, client, req)
case "tls-user":
req := exportTLSAuthorityRequest{
AuthType: types.UserCA,
UnpackPEM: false,
ExportPrivateKeys: exportSecrets,
}
return exportTLSAuthority(ctx, client, req)
case "db":
req := exportTLSAuthorityRequest{
AuthType: types.DatabaseCA,
UnpackPEM: false,
ExportPrivateKeys: exportSecrets,
}
return exportTLSAuthority(ctx, client, req)
case "db-der":
req := exportTLSAuthorityRequest{
AuthType: types.DatabaseCA,
UnpackPEM: true,
ExportPrivateKeys: exportSecrets,
}
return exportTLSAuthority(ctx, client, req)
case "db-client":
req := exportTLSAuthorityRequest{
AuthType: types.DatabaseClientCA,
UnpackPEM: false,
ExportPrivateKeys: exportSecrets,
}
return exportTLSAuthority(ctx, client, req)
case "db-client-der":
req := exportTLSAuthorityRequest{
AuthType: types.DatabaseClientCA,
UnpackPEM: true,
ExportPrivateKeys: exportSecrets,
}
return exportTLSAuthority(ctx, client, req)
case "tls-user-der", "windows":
req := exportTLSAuthorityRequest{
AuthType: types.UserCA,
UnpackPEM: true,
ExportPrivateKeys: exportSecrets,
}
return exportTLSAuthority(ctx, client, req)
case "saml-idp":
req := exportTLSAuthorityRequest{
AuthType: types.SAMLIDPCA,
UnpackPEM: true,
ExportPrivateKeys: exportSecrets,
}
return exportTLSAuthority(ctx, client, req)
}
// If none of the above auth-types was requested, means we are dealing with SSH HostCA or SSH UserCA.
// Either for adding SSH known hosts (~/.ssh/known_hosts) or authorized keys (`~/.ssh/authorized_keys`).
// Both are exported if AuthType is empty.
if req.AuthType == "" {
typesToExport = []types.CertAuthType{types.HostCA, types.UserCA}
} else {
authType := types.CertAuthType(req.AuthType)
if err := authType.Check(); err != nil {
return "", trace.Wrap(err)
}
typesToExport = []types.CertAuthType{authType}
}
localAuthName, err := client.GetDomainName(ctx)
if err != nil {
return "", trace.Wrap(err)
}
// fetch authorities via auth API (and only take local CAs, ignoring
// trusted ones)
var authorities []types.CertAuthority
for _, at := range typesToExport {
cas, err := client.GetCertAuthorities(ctx, at, exportSecrets)
if err != nil {
return "", trace.Wrap(err)
}
for _, ca := range cas {
if ca.GetClusterName() == localAuthName {
authorities = append(authorities, ca)
}
}
}
ret := strings.Builder{}
for _, ca := range authorities {
if exportSecrets {
for _, key := range ca.GetActiveKeys().SSH {
if req.ExportAuthorityFingerprint != "" {
fingerprint, err := sshutils.PrivateKeyFingerprint(key.PrivateKey)
if err != nil {
return "", trace.Wrap(err)
}
if fingerprint != req.ExportAuthorityFingerprint {
continue
}
}
ret.Write(key.PrivateKey)
ret.WriteString("\n")
}
continue
}
for _, key := range ca.GetTrustedSSHKeyPairs() {
if req.ExportAuthorityFingerprint != "" {
fingerprint, err := sshutils.AuthorizedKeyFingerprint(key.PublicKey)
if err != nil {
return "", trace.Wrap(err)
}
if fingerprint != req.ExportAuthorityFingerprint {
continue
}
}
// export certificates in the old 1.0 format where host and user
// certificate authorities were exported in the known_hosts format.
if req.UseCompatVersion {
castr, err := hostCAFormat(ca, key.PublicKey, client)
if err != nil {
return "", trace.Wrap(err)
}
ret.WriteString(castr)
continue
}
// export certificate authority in user or host ca format
var castr string
switch ca.GetType() {
case types.UserCA, types.OpenSSHCA:
castr, err = userOrOpenSSHCAFormat(ca, key.PublicKey)
case types.HostCA:
castr, err = hostCAFormat(ca, key.PublicKey, client)
default:
return "", trace.BadParameter("unknown user type: %q", ca.GetType())
}
if err != nil {
return "", trace.Wrap(err)
}
// write the export friendly string
ret.WriteString(castr)
}
}
return ret.String(), nil
}
type exportTLSAuthorityRequest struct {
AuthType types.CertAuthType
UnpackPEM bool
ExportPrivateKeys bool
}
func exportTLSAuthority(ctx context.Context, client auth.ClientI, req exportTLSAuthorityRequest) (string, error) {
clusterName, err := client.GetDomainName(ctx)
if err != nil {
return "", trace.Wrap(err)
}
certAuthority, err := client.GetCertAuthority(
ctx,
types.CertAuthID{Type: req.AuthType, DomainName: clusterName},
req.ExportPrivateKeys,
)
if err != nil {
return "", trace.Wrap(err)
}
if l := len(certAuthority.GetActiveKeys().TLS); l != 1 {
return "", trace.BadParameter("expected one TLS key pair, got %v", l)
}
keyPair := certAuthority.GetActiveKeys().TLS[0]
bytesToExport := keyPair.Cert
if req.ExportPrivateKeys {
bytesToExport = keyPair.Key
}
if !req.UnpackPEM {
return string(bytesToExport), nil
}
b, _ := pem.Decode(bytesToExport)
if b == nil {
return "", trace.BadParameter("invalid PEM data")
}
return string(b.Bytes), nil
}
// userCAFormat returns the certificate authority public key exported as a single
// line that can be placed in ~/.ssh/authorized_keys file. The format adheres to the
// man sshd (8) authorized_keys format, a space-separated list of: options, keytype,
// base64-encoded key, comment.
// For example:
//
// cert-authority AAA... type=user&clustername=cluster-a
//
// URL encoding is used to pass the CA type and cluster name into the comment field.
func userOrOpenSSHCAFormat(ca types.CertAuthority, keyBytes []byte) (string, error) {
return sshutils.MarshalAuthorizedKeysFormat(ca.GetClusterName(), keyBytes)
}
// hostCAFormat returns the certificate authority public key exported as a single line
// that can be placed in ~/.ssh/known_hosts. The format adheres to the man sshd (8)
// known_hosts format, a space-separated list of: marker, hosts, key, and comment.
// For example:
//
// @cert-authority *.cluster-a ssh-rsa AAA... type=host
//
// URL encoding is used to pass the CA type and allowed logins into the comment field.
func hostCAFormat(ca types.CertAuthority, keyBytes []byte, client auth.ClientI) (string, error) {
roles, err := services.FetchRoles(ca.GetRoles(), client, nil /* traits */)
if err != nil {
return "", trace.Wrap(err)
}
allowedLogins, _ := roles.GetLoginsForTTL(apidefaults.MinCertDuration + time.Second)
return sshutils.MarshalKnownHost(sshutils.KnownHost{
Hostname: ca.GetClusterName(),
AuthorizedKey: keyBytes,
Comment: map[string][]string{
"logins": allowedLogins,
},
})
}