forked from smallstep/certificates
-
Notifications
You must be signed in to change notification settings - Fork 0
/
onboard.go
212 lines (176 loc) · 5.41 KB
/
onboard.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
package commands
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/url"
"os"
"github.com/pkg/errors"
"github.com/smallstep/certificates/authority"
"github.com/smallstep/certificates/ca"
"github.com/smallstep/certificates/pki"
"github.com/smallstep/cli/command"
"github.com/smallstep/cli/crypto/randutil"
"github.com/smallstep/cli/errs"
"github.com/smallstep/cli/ui"
"github.com/smallstep/cli/utils"
"github.com/urfave/cli"
)
// defaultOnboardingURL is the production onboarding url, to use a development
// url use:
// export STEP_CA_ONBOARDING_URL=http://localhost:3002/onboarding/
const defaultOnboardingURL = "https://api.smallstep.com/onboarding/"
type onboardingConfiguration struct {
Name string `json:"name"`
DNS string `json:"dns"`
Address string `json:"address"`
password []byte
}
type onboardingPayload struct {
Fingerprint string `json:"fingerprint"`
}
type onboardingError struct {
StatusCode int `json:"statusCode"`
Message string `json:"message"`
}
func (e onboardingError) Error() string {
return e.Message
}
func init() {
command.Register(cli.Command{
Name: "onboard",
Usage: "configure and run step-ca from the onboarding guide",
UsageText: "**step-ca onboard** <token>",
Action: onboardAction,
Description: `**step-ca onboard** configures step certificates using the onboarding guide.
Open https://smallstep.com/onboarding in your browser and start the CA with the
given token:
'''
$ step-ca onboard <token>
'''
## POSITIONAL ARGUMENTS
<token>
: The token string provided by the onboarding guide.`,
})
}
func onboardAction(ctx *cli.Context) error {
if ctx.NArg() == 0 {
return cli.ShowCommandHelp(ctx, "onboard")
}
if err := errs.NumberOfArguments(ctx, 1); err != nil {
return err
}
// Get onboarding url
onboarding := defaultOnboardingURL
if v := os.Getenv("STEP_CA_ONBOARDING_URL"); v != "" {
onboarding = v
}
u, err := url.Parse(onboarding)
if err != nil {
return errors.Wrapf(err, "error parsing %s", onboarding)
}
ui.Println("Connecting to onboarding guide...")
token := ctx.Args().Get(0)
onboardingURL := u.ResolveReference(&url.URL{Path: token}).String()
res, err := http.Get(onboardingURL)
if err != nil {
return errors.Wrap(err, "error connecting onboarding guide")
}
if res.StatusCode >= 400 {
var msg onboardingError
if err := readJSON(res.Body, &msg); err != nil {
return errors.Wrap(err, "error unmarshaling response")
}
return errors.Wrap(msg, "error receiving onboarding guide")
}
var config onboardingConfiguration
if err := readJSON(res.Body, &config); err != nil {
return errors.Wrap(err, "error unmarshaling response")
}
password, err := randutil.ASCII(32)
if err != nil {
return err
}
config.password = []byte(password)
ui.Println("Initializing step-ca with the following configuration:")
ui.PrintSelected("Name", config.Name)
ui.PrintSelected("DNS", config.DNS)
ui.PrintSelected("Address", config.Address)
ui.PrintSelected("Password", password)
ui.Println()
caConfig, fp, err := onboardPKI(config)
if err != nil {
return err
}
payload, err := json.Marshal(onboardingPayload{Fingerprint: fp})
if err != nil {
return errors.Wrap(err, "error marshaling payload")
}
resp, err := http.Post(onboardingURL, "application/json", bytes.NewBuffer(payload))
if err != nil {
return errors.Wrap(err, "error connecting onboarding guide")
}
if resp.StatusCode >= 400 {
var msg onboardingError
if err := readJSON(resp.Body, &msg); err != nil {
ui.Printf("%s {{ \"error unmarshalling response: %v\" | yellow }}\n", ui.IconWarn, err)
} else {
ui.Printf("%s {{ \"error posting fingerprint: %s\" | yellow }}\n", ui.IconWarn, msg.Message)
}
} else {
resp.Body.Close()
}
ui.Println("Initialized!")
ui.Println("Step CA is starting. Please return to the onboarding guide in your browser to continue.")
srv, err := ca.New(caConfig, ca.WithPassword(config.password))
if err != nil {
fatal(err)
}
go ca.StopReloaderHandler(srv)
if err = srv.Run(); err != nil && err != http.ErrServerClosed {
fatal(err)
}
return nil
}
func onboardPKI(config onboardingConfiguration) (*authority.Config, string, error) {
p, err := pki.New(pki.GetPublicPath(), pki.GetSecretsPath(), pki.GetConfigPath())
if err != nil {
return nil, "", err
}
p.SetAddress(config.Address)
p.SetDNSNames([]string{config.DNS})
ui.Println("Generating root certificate...")
rootCrt, rootKey, err := p.GenerateRootCertificate(config.Name+" Root CA", config.password)
if err != nil {
return nil, "", err
}
ui.Println("Generating intermediate certificate...")
err = p.GenerateIntermediateCertificate(config.Name+" Intermediate CA", rootCrt, rootKey, config.password)
if err != nil {
return nil, "", err
}
// Generate provisioner
p.SetProvisioner("admin")
ui.Println("Generating admin provisioner...")
if err = p.GenerateKeyPairs(config.password); err != nil {
return nil, "", err
}
// Generate and write configuration
caConfig, err := p.GenerateConfig()
if err != nil {
return nil, "", err
}
b, err := json.MarshalIndent(caConfig, "", " ")
if err != nil {
return nil, "", errors.Wrapf(err, "error marshaling %s", p.GetCAConfigPath())
}
if err = utils.WriteFile(p.GetCAConfigPath(), b, 0666); err != nil {
return nil, "", errs.FileError(err, p.GetCAConfigPath())
}
return caConfig, p.GetRootFingerprint(), nil
}
func readJSON(r io.ReadCloser, v interface{}) error {
defer r.Close()
return json.NewDecoder(r).Decode(v)
}