This repository has been archived by the owner on Jan 24, 2020. It is now read-only.
forked from smallstep/cli
-
Notifications
You must be signed in to change notification settings - Fork 1
/
offline.go
275 lines (240 loc) · 7.55 KB
/
offline.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
package ca
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/pem"
"fmt"
"net/http"
"time"
"github.com/pkg/errors"
"github.com/smallstep/certificates/api"
"github.com/smallstep/certificates/authority"
"github.com/smallstep/certificates/authority/provisioner"
"github.com/smallstep/cli/crypto/pemutil"
"github.com/smallstep/cli/crypto/x509util"
"github.com/smallstep/cli/exec"
"github.com/smallstep/cli/jose"
"github.com/smallstep/cli/ui"
"github.com/smallstep/cli/utils"
"github.com/urfave/cli"
)
type caClient interface {
Sign(req *api.SignRequest) (*api.SignResponse, error)
Renew(tr http.RoundTripper) (*api.SignResponse, error)
Revoke(req *api.RevokeRequest, tr http.RoundTripper) (*api.RevokeResponse, error)
}
// offlineCA is a wrapper on top of the certificates authority methods that is
// used to sign certificates without an online CA.
type offlineCA struct {
authority *authority.Authority
config authority.Config
configFile string
}
// newOfflineCA initializes an offlineCA.
func newOfflineCA(configFile string) (*offlineCA, error) {
b, err := utils.ReadFile(configFile)
if err != nil {
return nil, err
}
var config authority.Config
if err := json.Unmarshal(b, &config); err != nil {
return nil, errors.Wrapf(err, "error reading %s", configFile)
}
if config.AuthorityConfig == nil || len(config.AuthorityConfig.Provisioners) == 0 {
return nil, errors.Errorf("error parsing %s: no provisioners found", configFile)
}
auth, err := authority.New(&config)
if err != nil {
return nil, err
}
return &offlineCA{
authority: auth,
config: config,
configFile: configFile,
}, nil
}
// VerifyClientCertificate verifies and validates the client cert/key pair
// using the offline CA root and intermediate certificates.
func (c *offlineCA) VerifyClientCert(certFile, keyFile string) error {
cert, err := pemutil.ReadCertificate(certFile, pemutil.WithFirstBlock())
if err != nil {
return err
}
key, err := pemutil.Read(keyFile)
if err != nil {
return err
}
certPem, err := pemutil.Serialize(cert)
if err != nil {
return err
}
keyPem, err := pemutil.Serialize(key)
if err != nil {
return err
}
// Validate that the certificate and key match
if _, err := tls.X509KeyPair(pem.EncodeToMemory(certPem), pem.EncodeToMemory(keyPem)); err != nil {
return errors.Wrap(err, "error loading x509 key pair")
}
rootPool, err := x509util.ReadCertPool(c.Root())
if err != nil {
return err
}
intermediatePool, err := x509util.ReadCertPool(c.config.IntermediateCert)
if err != nil {
return err
}
opts := x509.VerifyOptions{
Roots: rootPool,
Intermediates: intermediatePool,
}
if _, err := cert.Verify(opts); err != nil {
return errors.Wrapf(err, "failed to verify certificate")
}
return nil
}
// Audience returns the token audience.
func (c *offlineCA) Audience(tokType int) string {
switch tokType {
case revokeType:
return fmt.Sprintf("https://%s/revoke", c.config.DNSNames[0])
default:
return fmt.Sprintf("https://%s/sign", c.config.DNSNames[0])
}
}
// CaURL returns the CA URL using the first DNS entry.
func (c *offlineCA) CaURL() string {
return fmt.Sprintf("https://%s", c.config.DNSNames[0])
}
// Root returns the path of the file used as root certificate.
func (c *offlineCA) Root() string {
return c.config.Root.First()
}
// Provisioners returns the list of configured provisioners.
func (c *offlineCA) Provisioners() provisioner.List {
return c.config.AuthorityConfig.Provisioners
}
// Sign is a wrapper on top of certificates Authorize and Sign methods. It
// returns an api.SignResponse with the requested certificate and the
// intermediate.
func (c *offlineCA) Sign(req *api.SignRequest) (*api.SignResponse, error) {
opts, err := c.authority.Authorize(req.OTT)
if err != nil {
return nil, err
}
signOpts := provisioner.Options{
NotBefore: req.NotBefore,
NotAfter: req.NotAfter,
}
cert, ca, err := c.authority.Sign(req.CsrPEM.CertificateRequest, signOpts, opts...)
if err != nil {
return nil, err
}
return &api.SignResponse{
ServerPEM: api.Certificate{Certificate: cert},
CaPEM: api.Certificate{Certificate: ca},
TLSOptions: c.authority.GetTLSOptions(),
}, nil
}
// Renew is a wrapper on top of certificates Renew method. It returns an
// api.SignResponse with the requested certificate and the intermediate.
func (c *offlineCA) Renew(rt http.RoundTripper) (*api.SignResponse, error) {
// it should not panic as this is always internal code
tr := rt.(*http.Transport)
asn1Data := tr.TLSClientConfig.Certificates[0].Certificate[0]
peer, err := x509.ParseCertificate(asn1Data)
if err != nil {
return nil, errors.Wrap(err, "error parsing certificate")
}
// renew cert using authority
cert, ca, err := c.authority.Renew(peer)
if err != nil {
return nil, err
}
return &api.SignResponse{
ServerPEM: api.Certificate{Certificate: cert},
CaPEM: api.Certificate{Certificate: ca},
TLSOptions: c.authority.GetTLSOptions(),
}, nil
}
// Revoke is a wrapper on top of certificates Revoke method. It returns an
// api.RevokeResponse.
func (c *offlineCA) Revoke(req *api.RevokeRequest, rt http.RoundTripper) (*api.RevokeResponse, error) {
var (
opts = authority.RevokeOptions{
Serial: req.Serial,
Reason: req.Reason,
ReasonCode: req.ReasonCode,
PassiveOnly: req.Passive,
}
err error
)
if len(req.OTT) > 0 {
opts.OTT = req.OTT
opts.MTLS = false
} else {
// it should not panic as this is always internal code
tr := rt.(*http.Transport)
asn1Data := tr.TLSClientConfig.Certificates[0].Certificate[0]
opts.Crt, err = x509.ParseCertificate(asn1Data)
if err != nil {
return nil, errors.Wrap(err, "error parsing certificate")
}
opts.MTLS = true
}
// revoke cert using authority
if err := c.authority.Revoke(&opts); err != nil {
return nil, err
}
return &api.RevokeResponse{Status: "ok"}, nil
}
// GenerateToken creates the token used by the authority to authorize requests.
func (c *offlineCA) GenerateToken(ctx *cli.Context, typ int, subject string, sans []string, notBefore, notAfter time.Time) (string, error) {
// Use ca.json configuration for the root and audience
root := c.Root()
audience := c.Audience(typ)
// Get provisioner to use
provisioners := c.Provisioners()
p, err := provisionerPrompt(ctx, provisioners)
if err != nil {
return "", err
}
// With OIDC just run step oauth
if p, ok := p.(*provisioner.OIDC); ok {
out, err := exec.Step("oauth", "--oidc", "--bare",
"--provider", p.ConfigurationEndpoint,
"--client-id", p.ClientID, "--client-secret", p.ClientSecret)
if err != nil {
return "", err
}
return string(out), nil
}
// JWK provisioner
prov, ok := p.(*provisioner.JWK)
if !ok {
return "", errors.Errorf("unknown provisioner type %T", p)
}
kid := prov.Key.KeyID
issuer := prov.Name
encryptedKey := prov.EncryptedKey
// Decrypt encrypted key
opts := []jose.Option{
jose.WithUIOptions(ui.WithPromptTemplates(ui.PromptTemplates())),
}
if passwordFile := ctx.String("password-file"); len(passwordFile) != 0 {
opts = append(opts, jose.WithPasswordFile(passwordFile))
}
if len(encryptedKey) == 0 {
return "", errors.Errorf("provisioner '%s' does not have an 'encryptedKey' property", kid)
}
decrypted, err := jose.Decrypt("Please enter the password to decrypt the provisioner key", []byte(encryptedKey), opts...)
if err != nil {
return "", err
}
jwk := new(jose.JSONWebKey)
if err := json.Unmarshal(decrypted, jwk); err != nil {
return "", errors.Wrap(err, "error unmarshalling provisioning key")
}
return generateToken(typ, subject, sans, kid, issuer, audience, root, notBefore, notAfter, jwk)
}