| 1 |
package cautils |
| 2 |
|
| 3 |
import ( |
| 4 |
"context" |
| 5 |
"crypto/rand" |
| 6 |
"crypto/x509" |
| 7 |
"crypto/x509/pkix" |
| 8 |
"encoding/json" |
| 9 |
"encoding/pem" |
| 10 |
"fmt" |
| 11 |
"io/ioutil" |
| 12 |
"net/http" |
| 13 |
"os" |
| 14 |
"strings" |
| 15 |
"time" |
| 16 |
|
| 17 |
"github.com/pkg/errors" |
| 18 |
"github.com/smallstep/certificates/acme" |
| 19 |
acmeAPI "github.com/smallstep/certificates/acme/api" |
| 20 |
"github.com/smallstep/certificates/ca" |
| 21 |
"github.com/smallstep/certificates/pki" |
| 22 |
"github.com/smallstep/cli/crypto/keys" |
| 23 |
"github.com/smallstep/cli/errs" |
| 24 |
"github.com/smallstep/cli/flags" |
| 25 |
"github.com/smallstep/cli/jose" |
| 26 |
"github.com/smallstep/cli/ui" |
| 27 |
"github.com/smallstep/cli/utils" |
| 28 |
"github.com/urfave/cli" |
| 29 |
) |
| 30 |
|
| 31 |
func startHTTPServer(addr string, token string, keyAuth string) *http.Server { |
| 32 |
srv := &http.Server{Addr: addr} |
| 33 |
|
| 34 |
http.HandleFunc(fmt.Sprintf("/.well-known/acme-challenge/%s", token), func(w http.ResponseWriter, r *http.Request) { |
| 35 |
w.Header().Set("Content-Type", "application/octet-stream") |
| 36 |
w.Write([]byte(keyAuth)) |
| 37 |
}) |
| 38 |
|
| 39 |
go func() { |
| 40 |
|
| 41 |
if err := srv.ListenAndServe(); err != http.ErrServerClosed { |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
ui.Printf("\nListenAndServe(): %s\n", err) |
| 47 |
} |
| 48 |
}() |
| 49 |
|
| 50 |
|
| 51 |
return srv |
| 52 |
} |
| 53 |
|
| 54 |
type issueMode interface { |
| 55 |
Run() error |
| 56 |
Cleanup() error |
| 57 |
} |
| 58 |
|
| 59 |
type standaloneMode struct { |
| 60 |
identifier, token string |
| 61 |
key *jose.JSONWebKey |
| 62 |
listenAddr string |
| 63 |
srv *http.Server |
| 64 |
} |
| 65 |
|
| 66 |
func newStandaloneMode(identifier, listenAddr, token string, key *jose.JSONWebKey) *standaloneMode { |
| 67 |
return &standaloneMode{ |
| 68 |
identifier: identifier, |
| 69 |
listenAddr: listenAddr, |
| 70 |
token: token, |
| 71 |
key: key, |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
func (sm *standaloneMode) Run() error { |
| 76 |
ui.Printf("Using Standalone Mode HTTP challenge to validate %s", sm.identifier) |
| 77 |
keyAuth, err := acme.KeyAuthorization(sm.token, sm.key) |
| 78 |
if err != nil { |
| 79 |
return errors.Wrap(err, "error generating ACME key authorization") |
| 80 |
} |
| 81 |
sm.srv = startHTTPServer(sm.listenAddr, sm.token, keyAuth) |
| 82 |
return nil |
| 83 |
} |
| 84 |
|
| 85 |
func (sm *standaloneMode) Cleanup() error { |
| 86 |
ctx, cancel := context.WithTimeout(context.Background(), 1*time.Second) |
| 87 |
defer cancel() |
| 88 |
return errors.Wrap(sm.srv.Shutdown(ctx), "error gracefully shutting down server") |
| 89 |
} |
| 90 |
|
| 91 |
type webrootMode struct { |
| 92 |
dir, token, identifier string |
| 93 |
key *jose.JSONWebKey |
| 94 |
} |
| 95 |
|
| 96 |
func newWebrootMode(dir, token, identifier string, key *jose.JSONWebKey) *webrootMode { |
| 97 |
return &webrootMode{ |
| 98 |
dir: dir, |
| 99 |
token: token, |
| 100 |
identifier: identifier, |
| 101 |
key: key, |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
func (wm *webrootMode) Run() error { |
| 106 |
ui.Printf("Using Webroot Mode HTTP challenge to validate %s", wm.identifier) |
| 107 |
keyAuth, err := acme.KeyAuthorization(wm.token, wm.key) |
| 108 |
if err != nil { |
| 109 |
return errors.Wrap(err, "error generating ACME key authorization") |
| 110 |
} |
| 111 |
_, err = os.Stat(wm.dir) |
| 112 |
switch { |
| 113 |
case os.IsNotExist(err): |
| 114 |
return errors.Errorf("webroot directory %s does not exist", wm.dir) |
| 115 |
case err != nil: |
| 116 |
return errors.Wrapf(err, "error checking for directory %s", wm.dir) |
| 117 |
} |
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
|
| 123 |
chPath := fmt.Sprintf("%s/.well-known/acme-challenge", wm.dir) |
| 124 |
if _, err = os.Stat(chPath); os.IsNotExist(err) { |
| 125 |
if err = os.MkdirAll(chPath, 0755); err != nil { |
| 126 |
return errors.Wrapf(err, "error creating directory path %s", chPath) |
| 127 |
} |
| 128 |
} |
| 129 |
|
| 130 |
return errors.Wrapf(ioutil.WriteFile(fmt.Sprintf("%s/%s", chPath, wm.token), []byte(keyAuth), 0644), |
| 131 |
"error writing key authorization file %s", chPath+wm.token) |
| 132 |
} |
| 133 |
|
| 134 |
func (wm *webrootMode) Cleanup() error { |
| 135 |
return errors.Wrap(os.Remove(fmt.Sprintf("%s/.well-known/acme-challenge/%s", |
| 136 |
wm.dir, wm.token)), "error removing ACME challenge file") |
| 137 |
} |
| 138 |
|
| 139 |
func serveAndValidateHTTPChallenge(ctx *cli.Context, ac *ca.ACMEClient, ch *acme.Challenge, identifier string) error { |
| 140 |
var mode issueMode |
| 141 |
if ctx.Bool("standalone") { |
| 142 |
mode = newStandaloneMode(identifier, ctx.String("http-listen"), ch.Token, ac.Key) |
| 143 |
} else { |
| 144 |
mode = newWebrootMode(ctx.String("webroot"), ch.Token, identifier, ac.Key) |
| 145 |
} |
| 146 |
if err := mode.Run(); err != nil { |
| 147 |
ui.Printf(" Error!\n\n") |
| 148 |
mode.Cleanup() |
| 149 |
return err |
| 150 |
} |
| 151 |
ui.Printf(" .") |
| 152 |
|
| 153 |
if err := ac.ValidateChallenge(ch.URL); err != nil { |
| 154 |
ui.Printf(" Error!\n\n") |
| 155 |
mode.Cleanup() |
| 156 |
return errors.Wrapf(err, "error validating ACME Challenge at %s", ch.URL) |
| 157 |
} |
| 158 |
var ( |
| 159 |
isValid = false |
| 160 |
vch *acme.Challenge |
| 161 |
err error |
| 162 |
) |
| 163 |
for attempts := 0; attempts < 10; attempts++ { |
| 164 |
time.Sleep(1 * time.Second) |
| 165 |
ui.Printf(".") |
| 166 |
vch, err = ac.GetChallenge(ch.URL) |
| 167 |
if err != nil { |
| 168 |
ui.Printf(" Error!\n\n") |
| 169 |
mode.Cleanup() |
| 170 |
return errors.Wrapf(err, "error retrieving ACME Challenge at %s", ch.URL) |
| 171 |
} |
| 172 |
if vch.Status == "valid" { |
| 173 |
isValid = true |
| 174 |
break |
| 175 |
} |
| 176 |
} |
| 177 |
if !isValid { |
| 178 |
ui.Printf(" Error!\n\n") |
| 179 |
mode.Cleanup() |
| 180 |
return errors.Errorf("Unable to validate challenge: %+v", vch) |
| 181 |
} |
| 182 |
if err := mode.Cleanup(); err != nil { |
| 183 |
return err |
| 184 |
} |
| 185 |
ui.Printf(" done!\n") |
| 186 |
return nil |
| 187 |
} |
| 188 |
|
| 189 |
func authorizeOrder(ctx *cli.Context, ac *ca.ACMEClient, o *acme.Order) error { |
| 190 |
for _, azURL := range o.AuthorizationURLs { |
| 191 |
az, err := ac.GetAuthz(azURL) |
| 192 |
if err != nil { |
| 193 |
return errors.Wrapf(err, "error retrieving ACME Authz at %s", azURL) |
| 194 |
} |
| 195 |
|
| 196 |
ident := az.Identifier.Value |
| 197 |
if az.Wildcard { |
| 198 |
ident = "*." + ident |
| 199 |
} |
| 200 |
|
| 201 |
chValidated := false |
| 202 |
for _, ch := range az.Challenges { |
| 203 |
|
| 204 |
if ch.Type == "http-01" { |
| 205 |
if err := serveAndValidateHTTPChallenge(ctx, ac, ch, ident); err != nil { |
| 206 |
return err |
| 207 |
} |
| 208 |
chValidated = true |
| 209 |
break |
| 210 |
} |
| 211 |
} |
| 212 |
if !chValidated { |
| 213 |
return errors.Errorf("unable to validate any challenges for identifier: %s", ident) |
| 214 |
} |
| 215 |
} |
| 216 |
return nil |
| 217 |
} |
| 218 |
|
| 219 |
func finalizeOrder(ac *ca.ACMEClient, o *acme.Order, csr *x509.CertificateRequest) (*acme.Order, error) { |
| 220 |
var ( |
| 221 |
err error |
| 222 |
ro, fo *acme.Order |
| 223 |
isReady, isValid bool |
| 224 |
) |
| 225 |
ui.Printf("Waiting for Order to be 'ready' for finalization .") |
| 226 |
for i := 9; i >= 0; i-- { |
| 227 |
time.Sleep(1 * time.Second) |
| 228 |
ui.Printf(".") |
| 229 |
ro, err = ac.GetOrder(o.ID) |
| 230 |
if err != nil { |
| 231 |
return nil, errors.Wrapf(err, "error retrieving order %s", o.ID) |
| 232 |
} |
| 233 |
if ro.Status == "ready" { |
| 234 |
isReady = true |
| 235 |
ui.Printf(" done!\n") |
| 236 |
break |
| 237 |
} |
| 238 |
} |
| 239 |
if !isReady { |
| 240 |
ui.Printf(" Error!\n\n") |
| 241 |
return nil, errors.Errorf("Unable to validate order: %+v", ro) |
| 242 |
} |
| 243 |
|
| 244 |
ui.Printf("Finalizing Order .") |
| 245 |
if err = ac.FinalizeOrder(o.FinalizeURL, csr); err != nil { |
| 246 |
return nil, errors.Wrapf(err, "error finalizing order") |
| 247 |
} |
| 248 |
|
| 249 |
for i := 9; i >= 0; i-- { |
| 250 |
time.Sleep(1 * time.Second) |
| 251 |
ui.Printf(".") |
| 252 |
fo, err = ac.GetOrder(o.ID) |
| 253 |
if err != nil { |
| 254 |
return nil, errors.Wrapf(err, "error retrieving order %s", o.ID) |
| 255 |
} |
| 256 |
if fo.Status == "valid" { |
| 257 |
isValid = true |
| 258 |
ui.Printf(" done!\n") |
| 259 |
break |
| 260 |
} |
| 261 |
} |
| 262 |
if !isValid { |
| 263 |
ui.Printf(" Error!\n\n") |
| 264 |
return nil, errors.Errorf("Unable to finalize order: %+v", fo) |
| 265 |
} |
| 266 |
|
| 267 |
return fo, nil |
| 268 |
} |
| 269 |
|
| 270 |
func validateSANsForACME(sans []string) ([]string, error) { |
| 271 |
dnsNames, ips, emails, uris := splitSANs(sans) |
| 272 |
if len(ips) > 0 || len(emails) > 0 || len(uris) > 0 { |
| 273 |
return nil, errors.New("IP Address, Email Address, and URI SANs are not supported for ACME flow") |
| 274 |
} |
| 275 |
for _, dns := range dnsNames { |
| 276 |
if strings.Contains(dns, "*") { |
| 277 |
return nil, errors.Errorf("wildcard dnsnames (%s) require dns validation, "+ |
| 278 |
"which is currently not implemented in this client", dns) |
| 279 |
} |
| 280 |
} |
| 281 |
return dnsNames, nil |
| 282 |
} |
| 283 |
|
| 284 |
type acmeFlowOp func(*acmeFlow) error |
| 285 |
|
| 286 |
func withProvisionerName(name string) acmeFlowOp { |
| 287 |
return func(af *acmeFlow) error { |
| 288 |
af.provisionerName = name |
| 289 |
return nil |
| 290 |
} |
| 291 |
} |
| 292 |
|
| 293 |
func withCSR(csr *x509.CertificateRequest) acmeFlowOp { |
| 294 |
return func(af *acmeFlow) error { |
| 295 |
af.csr = csr |
| 296 |
af.subject = csr.Subject.CommonName |
| 297 |
af.sans = csr.DNSNames |
| 298 |
return nil |
| 299 |
} |
| 300 |
} |
| 301 |
|
| 302 |
func withSubjectSANs(sub string, sans []string) acmeFlowOp { |
| 303 |
return func(af *acmeFlow) error { |
| 304 |
af.subject = sub |
| 305 |
af.sans = sans |
| 306 |
return nil |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
type acmeFlow struct { |
| 311 |
ctx *cli.Context |
| 312 |
provisionerName string |
| 313 |
csr *x509.CertificateRequest |
| 314 |
priv interface{} |
| 315 |
subject string |
| 316 |
sans []string |
| 317 |
acmeDir string |
| 318 |
} |
| 319 |
|
| 320 |
func newACMEFlow(ctx *cli.Context, ops ...acmeFlowOp) (*acmeFlow, error) { |
| 321 |
|
| 322 |
if ctx.Bool("offline") { |
| 323 |
return nil, errors.New("offline mode and ACME are mutually exclusive") |
| 324 |
} |
| 325 |
|
| 326 |
isStandalone, webroot := ctx.Bool("standalone"), ctx.String("webroot") |
| 327 |
switch { |
| 328 |
case isStandalone && len(webroot) > 0: |
| 329 |
return nil, errs.MutuallyExclusiveFlags(ctx, "standalone", "webroot") |
| 330 |
case !isStandalone && len(webroot) == 0: |
| 331 |
if err := ctx.Set("standalone", "true"); err != nil { |
| 332 |
return nil, errors.Wrap(err, "error setting 'standalone' value in cli ctx") |
| 333 |
} |
| 334 |
} |
| 335 |
|
| 336 |
af := new(acmeFlow) |
| 337 |
for _, op := range ops { |
| 338 |
if err := op(af); err != nil { |
| 339 |
return nil, err |
| 340 |
} |
| 341 |
} |
| 342 |
if len(af.sans) == 0 { |
| 343 |
af.sans = []string{af.subject} |
| 344 |
} |
| 345 |
|
| 346 |
af.ctx = ctx |
| 347 |
|
| 348 |
af.acmeDir = ctx.String("acme") |
| 349 |
if len(af.acmeDir) == 0 { |
| 350 |
caURL, err := flags.ParseCaURL(ctx) |
| 351 |
if err != nil { |
| 352 |
return nil, err |
| 353 |
} |
| 354 |
if len(af.provisionerName) == 0 { |
| 355 |
return nil, errors.New("acme flow expected provisioner ID") |
| 356 |
} |
| 357 |
af.acmeDir = fmt.Sprintf("%s/acme/%s/directory", caURL, af.provisionerName) |
| 358 |
} |
| 359 |
|
| 360 |
return af, nil |
| 361 |
} |
| 362 |
|
| 363 |
func (af *acmeFlow) GetCertificate() ([]*x509.Certificate, error) { |
| 364 |
dnsNames, err := validateSANsForACME(af.sans) |
| 365 |
if err != nil { |
| 366 |
return nil, err |
| 367 |
} |
| 368 |
|
| 369 |
var idents []acme.Identifier |
| 370 |
for _, dns := range dnsNames { |
| 371 |
idents = append(idents, acme.Identifier{ |
| 372 |
Type: "dns", |
| 373 |
Value: dns, |
| 374 |
}) |
| 375 |
} |
| 376 |
|
| 377 |
var ( |
| 378 |
orderPayload []byte |
| 379 |
clientOps []ca.ClientOption |
| 380 |
) |
| 381 |
if strings.Contains(af.acmeDir, "letsencrypt") { |
| 382 |
|
| 383 |
if af.ctx.IsSet("not-before") || af.ctx.IsSet("not-after") { |
| 384 |
return nil, errors.New("LetsEncrypt public CA does not support NotBefore/NotAfter " + |
| 385 |
"attributes for certificates. Instead, each certificate has a default lifetime of 3 months.") |
| 386 |
} |
| 387 |
|
| 388 |
clientOps = append(clientOps, ca.WithTransport(http.DefaultTransport)) |
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
hasSubject := false |
| 393 |
for _, n := range idents { |
| 394 |
if n.Value == af.subject { |
| 395 |
hasSubject = true |
| 396 |
} |
| 397 |
} |
| 398 |
if !hasSubject { |
| 399 |
dnsNames = append(dnsNames, af.subject) |
| 400 |
idents = append(idents, acme.Identifier{ |
| 401 |
Type: "dns", |
| 402 |
Value: af.subject, |
| 403 |
}) |
| 404 |
} |
| 405 |
orderPayload, err = json.Marshal(struct { |
| 406 |
Identifiers []acme.Identifier |
| 407 |
}{Identifiers: idents}) |
| 408 |
if err != nil { |
| 409 |
return nil, errors.Wrap(err, "error marshaling new letsencrypt order request") |
| 410 |
} |
| 411 |
} else { |
| 412 |
|
| 413 |
root := af.ctx.String("root") |
| 414 |
if len(root) == 0 { |
| 415 |
root = pki.GetRootCAPath() |
| 416 |
if _, err := os.Stat(root); err != nil { |
| 417 |
return nil, errs.RequiredFlag(af.ctx, "root") |
| 418 |
} |
| 419 |
} |
| 420 |
clientOps = append(clientOps, ca.WithRootFile(root)) |
| 421 |
|
| 422 |
nbf, naf, err := flags.ParseTimeDuration(af.ctx) |
| 423 |
if err != nil { |
| 424 |
return nil, err |
| 425 |
} |
| 426 |
|
| 427 |
nor := acmeAPI.NewOrderRequest{ |
| 428 |
Identifiers: idents, |
| 429 |
NotAfter: naf.Time(), |
| 430 |
NotBefore: nbf.Time(), |
| 431 |
} |
| 432 |
orderPayload, err = json.Marshal(nor) |
| 433 |
if err != nil { |
| 434 |
return nil, errors.Wrap(err, "error marshaling new order request") |
| 435 |
} |
| 436 |
} |
| 437 |
|
| 438 |
ac, err := ca.NewACMEClient(af.acmeDir, af.ctx.StringSlice("contact"), clientOps...) |
| 439 |
if err != nil { |
| 440 |
return nil, errors.Wrapf(err, "error initializing ACME client with server %s", af.acmeDir) |
| 441 |
} |
| 442 |
|
| 443 |
o, err := ac.NewOrder(orderPayload) |
| 444 |
if err != nil { |
| 445 |
return nil, errors.Wrapf(err, "error creating new ACME order") |
| 446 |
} |
| 447 |
|
| 448 |
if err = authorizeOrder(af.ctx, ac, o); err != nil { |
| 449 |
return nil, err |
| 450 |
} |
| 451 |
|
| 452 |
if af.csr == nil { |
| 453 |
insecure := af.ctx.Bool("insecure") |
| 454 |
kty, crv, size, err := utils.GetKeyDetailsFromCLI(af.ctx, insecure, "kty", "curve", "size") |
| 455 |
if err != nil { |
| 456 |
return nil, err |
| 457 |
} |
| 458 |
af.priv, err = keys.GenerateKey(kty, crv, size) |
| 459 |
if err != nil { |
| 460 |
return nil, errors.Wrap(err, "error generating private key") |
| 461 |
} |
| 462 |
|
| 463 |
_csr := &x509.CertificateRequest{ |
| 464 |
Subject: pkix.Name{ |
| 465 |
CommonName: af.subject, |
| 466 |
}, |
| 467 |
DNSNames: dnsNames, |
| 468 |
} |
| 469 |
var csrBytes []byte |
| 470 |
csrBytes, err = x509.CreateCertificateRequest(rand.Reader, _csr, af.priv) |
| 471 |
if err != nil { |
| 472 |
return nil, errors.Wrap(err, "error creating certificate request") |
| 473 |
} |
| 474 |
af.csr, err = x509.ParseCertificateRequest(csrBytes) |
| 475 |
if err != nil { |
| 476 |
return nil, errors.Wrap(err, "error parsing certificate request") |
| 477 |
} |
| 478 |
} |
| 479 |
|
| 480 |
fo, err := finalizeOrder(ac, o, af.csr) |
| 481 |
if err != nil { |
| 482 |
return nil, err |
| 483 |
} |
| 484 |
|
| 485 |
leaf, chain, err := ac.GetCertificate(fo.CertificateURL) |
| 486 |
if err != nil { |
| 487 |
return nil, errors.Wrapf(err, "error getting certificate") |
| 488 |
} |
| 489 |
return append([]*x509.Certificate{leaf}, chain...), nil |
| 490 |
} |
| 491 |
|
| 492 |
func writeCert(chain []*x509.Certificate, certFile string) error { |
| 493 |
var certBytes = []byte{} |
| 494 |
for _, c := range chain { |
| 495 |
certBytes = append(certBytes, pem.EncodeToMemory(&pem.Block{ |
| 496 |
Type: "CERTIFICATE", |
| 497 |
Bytes: c.Raw, |
| 498 |
})...) |
| 499 |
} |
| 500 |
|
| 501 |
if err := utils.WriteFile(certFile, certBytes, 0600); err != nil { |
| 502 |
return errs.FileError(err, certFile) |
| 503 |
} |
| 504 |
return nil |
| 505 |
} |