forked from TrueCloudLab/certificates
[acme] Continued work on acme db interface (wip)
This commit is contained in:
parent
34859551ef
commit
31ad7f2e9b
12 changed files with 1385 additions and 1025 deletions
|
@ -319,3 +319,13 @@ func (a *Authority) GetCertificate(accID, certID string) ([]byte, error) {
|
|||
}
|
||||
return cert.toACME(a.db, a.dir)
|
||||
}
|
||||
|
||||
type httpGetter func(string) (*http.Response, error)
|
||||
type lookupTxt func(string) ([]string, error)
|
||||
type tlsDialer func(network, addr string, config *tls.Config) (*tls.Conn, error)
|
||||
|
||||
type validateOptions struct {
|
||||
httpGet httpGetter
|
||||
lookupTxt lookupTxt
|
||||
tlsDial tlsDialer
|
||||
}
|
||||
|
|
347
acme/authz.go
347
acme/authz.go
|
@ -1,347 +0,0 @@
|
|||
package acme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/smallstep/nosql"
|
||||
)
|
||||
|
||||
var defaultExpiryDuration = time.Hour * 24
|
||||
|
||||
// Authz is a subset of the Authz type containing only those attributes
|
||||
// required for responses in the ACME protocol.
|
||||
type Authz struct {
|
||||
Identifier Identifier `json:"identifier"`
|
||||
Status string `json:"status"`
|
||||
Expires string `json:"expires"`
|
||||
Challenges []*Challenge `json:"challenges"`
|
||||
Wildcard bool `json:"wildcard"`
|
||||
ID string `json:"-"`
|
||||
}
|
||||
|
||||
// ToLog enables response logging.
|
||||
func (a *Authz) ToLog() (interface{}, error) {
|
||||
b, err := json.Marshal(a)
|
||||
if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error marshaling authz for logging"))
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// GetID returns the Authz ID.
|
||||
func (a *Authz) GetID() string {
|
||||
return a.ID
|
||||
}
|
||||
|
||||
// authz is the interface that the various authz types must implement.
|
||||
type authz interface {
|
||||
save(nosql.DB, authz) error
|
||||
clone() *baseAuthz
|
||||
getID() string
|
||||
getAccountID() string
|
||||
getType() string
|
||||
getIdentifier() Identifier
|
||||
getStatus() string
|
||||
getExpiry() time.Time
|
||||
getWildcard() bool
|
||||
getChallenges() []string
|
||||
getCreated() time.Time
|
||||
updateStatus(db nosql.DB) (authz, error)
|
||||
toACME(context.Context, nosql.DB, *directory) (*Authz, error)
|
||||
}
|
||||
|
||||
// baseAuthz is the base authz type that others build from.
|
||||
type baseAuthz struct {
|
||||
ID string `json:"id"`
|
||||
AccountID string `json:"accountID"`
|
||||
Identifier Identifier `json:"identifier"`
|
||||
Status string `json:"status"`
|
||||
Expires time.Time `json:"expires"`
|
||||
Challenges []string `json:"challenges"`
|
||||
Wildcard bool `json:"wildcard"`
|
||||
Created time.Time `json:"created"`
|
||||
Error *Error `json:"error"`
|
||||
}
|
||||
|
||||
func newBaseAuthz(accID string, identifier Identifier) (*baseAuthz, error) {
|
||||
id, err := randID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
now := clock.Now()
|
||||
ba := &baseAuthz{
|
||||
ID: id,
|
||||
AccountID: accID,
|
||||
Status: StatusPending,
|
||||
Created: now,
|
||||
Expires: now.Add(defaultExpiryDuration),
|
||||
Identifier: identifier,
|
||||
}
|
||||
|
||||
if strings.HasPrefix(identifier.Value, "*.") {
|
||||
ba.Wildcard = true
|
||||
ba.Identifier = Identifier{
|
||||
Value: strings.TrimPrefix(identifier.Value, "*."),
|
||||
Type: identifier.Type,
|
||||
}
|
||||
}
|
||||
|
||||
return ba, nil
|
||||
}
|
||||
|
||||
// getID returns the ID of the authz.
|
||||
func (ba *baseAuthz) getID() string {
|
||||
return ba.ID
|
||||
}
|
||||
|
||||
// getAccountID returns the Account ID that created the authz.
|
||||
func (ba *baseAuthz) getAccountID() string {
|
||||
return ba.AccountID
|
||||
}
|
||||
|
||||
// getType returns the type of the authz.
|
||||
func (ba *baseAuthz) getType() string {
|
||||
return ba.Identifier.Type
|
||||
}
|
||||
|
||||
// getIdentifier returns the identifier for the authz.
|
||||
func (ba *baseAuthz) getIdentifier() Identifier {
|
||||
return ba.Identifier
|
||||
}
|
||||
|
||||
// getStatus returns the status of the authz.
|
||||
func (ba *baseAuthz) getStatus() string {
|
||||
return ba.Status
|
||||
}
|
||||
|
||||
// getWildcard returns true if the authz identifier has a '*', false otherwise.
|
||||
func (ba *baseAuthz) getWildcard() bool {
|
||||
return ba.Wildcard
|
||||
}
|
||||
|
||||
// getChallenges returns the authz challenge IDs.
|
||||
func (ba *baseAuthz) getChallenges() []string {
|
||||
return ba.Challenges
|
||||
}
|
||||
|
||||
// getExpiry returns the expiration time of the authz.
|
||||
func (ba *baseAuthz) getExpiry() time.Time {
|
||||
return ba.Expires
|
||||
}
|
||||
|
||||
// getCreated returns the created time of the authz.
|
||||
func (ba *baseAuthz) getCreated() time.Time {
|
||||
return ba.Created
|
||||
}
|
||||
|
||||
// toACME converts the internal Authz type into the public acmeAuthz type for
|
||||
// presentation in the ACME protocol.
|
||||
func (ba *baseAuthz) toACME(ctx context.Context, db nosql.DB, dir *directory) (*Authz, error) {
|
||||
var chs = make([]*Challenge, len(ba.Challenges))
|
||||
for i, chID := range ba.Challenges {
|
||||
ch, err := getChallenge(db, chID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
chs[i], err = ch.toACME(ctx, db, dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &Authz{
|
||||
Identifier: ba.Identifier,
|
||||
Status: ba.getStatus(),
|
||||
Challenges: chs,
|
||||
Wildcard: ba.getWildcard(),
|
||||
Expires: ba.Expires.Format(time.RFC3339),
|
||||
ID: ba.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (ba *baseAuthz) save(db nosql.DB, old authz) error {
|
||||
var (
|
||||
err error
|
||||
oldB, newB []byte
|
||||
)
|
||||
if old == nil {
|
||||
oldB = nil
|
||||
} else {
|
||||
if oldB, err = json.Marshal(old); err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err, "error marshaling old authz"))
|
||||
}
|
||||
}
|
||||
if newB, err = json.Marshal(ba); err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err, "error marshaling new authz"))
|
||||
}
|
||||
_, swapped, err := db.CmpAndSwap(authzTable, []byte(ba.ID), oldB, newB)
|
||||
switch {
|
||||
case err != nil:
|
||||
return ServerInternalErr(errors.Wrapf(err, "error storing authz"))
|
||||
case !swapped:
|
||||
return ServerInternalErr(errors.Errorf("error storing authz; " +
|
||||
"value has changed since last read"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (ba *baseAuthz) clone() *baseAuthz {
|
||||
u := *ba
|
||||
return &u
|
||||
}
|
||||
|
||||
func (ba *baseAuthz) parent() authz {
|
||||
return &dnsAuthz{ba}
|
||||
}
|
||||
|
||||
// updateStatus attempts to update the status on a baseAuthz and stores the
|
||||
// updating object if necessary.
|
||||
func (ba *baseAuthz) updateStatus(db nosql.DB) (authz, error) {
|
||||
newAuthz := ba.clone()
|
||||
|
||||
now := time.Now().UTC()
|
||||
switch ba.Status {
|
||||
case StatusInvalid:
|
||||
return ba.parent(), nil
|
||||
case StatusValid:
|
||||
return ba.parent(), nil
|
||||
case StatusPending:
|
||||
// check expiry
|
||||
if now.After(ba.Expires) {
|
||||
newAuthz.Status = StatusInvalid
|
||||
newAuthz.Error = MalformedErr(errors.New("authz has expired"))
|
||||
break
|
||||
}
|
||||
|
||||
var isValid = false
|
||||
for _, chID := range ba.Challenges {
|
||||
ch, err := getChallenge(db, chID)
|
||||
if err != nil {
|
||||
return ba, err
|
||||
}
|
||||
if ch.getStatus() == StatusValid {
|
||||
isValid = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !isValid {
|
||||
return ba.parent(), nil
|
||||
}
|
||||
newAuthz.Status = StatusValid
|
||||
newAuthz.Error = nil
|
||||
default:
|
||||
return nil, ServerInternalErr(errors.Errorf("unrecognized authz status: %s", ba.Status))
|
||||
}
|
||||
|
||||
if err := newAuthz.save(db, ba); err != nil {
|
||||
return ba, err
|
||||
}
|
||||
return newAuthz.parent(), nil
|
||||
}
|
||||
|
||||
// unmarshalAuthz unmarshals an authz type into the correct sub-type.
|
||||
func unmarshalAuthz(data []byte) (authz, error) {
|
||||
var getType struct {
|
||||
Identifier Identifier `json:"identifier"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &getType); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling authz type"))
|
||||
}
|
||||
|
||||
switch getType.Identifier.Type {
|
||||
case "dns":
|
||||
var ba baseAuthz
|
||||
if err := json.Unmarshal(data, &ba); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling authz type into dnsAuthz"))
|
||||
}
|
||||
return &dnsAuthz{&ba}, nil
|
||||
default:
|
||||
return nil, ServerInternalErr(errors.Errorf("unexpected authz type %s",
|
||||
getType.Identifier.Type))
|
||||
}
|
||||
}
|
||||
|
||||
// dnsAuthz represents a dns acme authorization.
|
||||
type dnsAuthz struct {
|
||||
*baseAuthz
|
||||
}
|
||||
|
||||
// newAuthz returns a new acme authorization object based on the identifier
|
||||
// type.
|
||||
func newAuthz(db nosql.DB, accID string, identifier Identifier) (a authz, err error) {
|
||||
switch identifier.Type {
|
||||
case "dns":
|
||||
a, err = newDNSAuthz(db, accID, identifier)
|
||||
default:
|
||||
err = MalformedErr(errors.Errorf("unexpected authz type %s",
|
||||
identifier.Type))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// newDNSAuthz returns a new dns acme authorization object.
|
||||
func newDNSAuthz(db nosql.DB, accID string, identifier Identifier) (authz, error) {
|
||||
ba, err := newBaseAuthz(accID, identifier)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ba.Challenges = []string{}
|
||||
if !ba.Wildcard {
|
||||
// http and alpn challenges are only permitted if the DNS is not a wildcard dns.
|
||||
ch1, err := newHTTP01Challenge(db, ChallengeOptions{
|
||||
AccountID: accID,
|
||||
AuthzID: ba.ID,
|
||||
Identifier: ba.Identifier})
|
||||
if err != nil {
|
||||
return nil, Wrap(err, "error creating http challenge")
|
||||
}
|
||||
ba.Challenges = append(ba.Challenges, ch1.getID())
|
||||
|
||||
ch2, err := newTLSALPN01Challenge(db, ChallengeOptions{
|
||||
AccountID: accID,
|
||||
AuthzID: ba.ID,
|
||||
Identifier: ba.Identifier,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, Wrap(err, "error creating alpn challenge")
|
||||
}
|
||||
ba.Challenges = append(ba.Challenges, ch2.getID())
|
||||
}
|
||||
ch3, err := newDNS01Challenge(db, ChallengeOptions{
|
||||
AccountID: accID,
|
||||
AuthzID: ba.ID,
|
||||
Identifier: identifier})
|
||||
if err != nil {
|
||||
return nil, Wrap(err, "error creating dns challenge")
|
||||
}
|
||||
ba.Challenges = append(ba.Challenges, ch3.getID())
|
||||
|
||||
da := &dnsAuthz{ba}
|
||||
if err := da.save(db, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return da, nil
|
||||
}
|
||||
|
||||
// getAuthz retrieves and unmarshals an ACME authz type from the database.
|
||||
func getAuthz(db nosql.DB, id string) (authz, error) {
|
||||
b, err := db.Get(authzTable, []byte(id))
|
||||
if nosql.IsErrNotFound(err) {
|
||||
return nil, MalformedErr(errors.Wrapf(err, "authz %s not found", id))
|
||||
} else if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error loading authz %s", id))
|
||||
}
|
||||
az, err := unmarshalAuthz(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return az, nil
|
||||
}
|
|
@ -1,620 +0,0 @@
|
|||
package acme
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"crypto/tls"
|
||||
"encoding/asn1"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/smallstep/nosql"
|
||||
"go.step.sm/crypto/jose"
|
||||
)
|
||||
|
||||
// Challenge is a subset of the challenge type containing only those attributes
|
||||
// required for responses in the ACME protocol.
|
||||
type Challenge struct {
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status"`
|
||||
Token string `json:"token"`
|
||||
Validated string `json:"validated,omitempty"`
|
||||
URL string `json:"url"`
|
||||
Error *AError `json:"error,omitempty"`
|
||||
ID string `json:"-"`
|
||||
AuthzID string `json:"-"`
|
||||
}
|
||||
|
||||
// ToLog enables response logging.
|
||||
func (c *Challenge) ToLog() (interface{}, error) {
|
||||
b, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error marshaling challenge for logging"))
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// GetID returns the Challenge ID.
|
||||
func (c *Challenge) GetID() string {
|
||||
return c.ID
|
||||
}
|
||||
|
||||
// GetAuthzID returns the parent Authz ID that owns the Challenge.
|
||||
func (c *Challenge) GetAuthzID() string {
|
||||
return c.AuthzID
|
||||
}
|
||||
|
||||
type httpGetter func(string) (*http.Response, error)
|
||||
type lookupTxt func(string) ([]string, error)
|
||||
type tlsDialer func(network, addr string, config *tls.Config) (*tls.Conn, error)
|
||||
|
||||
type validateOptions struct {
|
||||
httpGet httpGetter
|
||||
lookupTxt lookupTxt
|
||||
tlsDial tlsDialer
|
||||
}
|
||||
|
||||
// challenge is the interface ACME challenege types must implement.
|
||||
type challenge interface {
|
||||
save(db nosql.DB, swap challenge) error
|
||||
validate(nosql.DB, *jose.JSONWebKey, validateOptions) (challenge, error)
|
||||
getType() string
|
||||
getError() *AError
|
||||
getValue() string
|
||||
getStatus() string
|
||||
getID() string
|
||||
getAuthzID() string
|
||||
getToken() string
|
||||
clone() *baseChallenge
|
||||
getAccountID() string
|
||||
getValidated() time.Time
|
||||
getCreated() time.Time
|
||||
toACME(context.Context, nosql.DB, *directory) (*Challenge, error)
|
||||
}
|
||||
|
||||
// ChallengeOptions is the type used to created a new Challenge.
|
||||
type ChallengeOptions struct {
|
||||
AccountID string
|
||||
AuthzID string
|
||||
Identifier Identifier
|
||||
}
|
||||
|
||||
// baseChallenge is the base Challenge type that others build from.
|
||||
type baseChallenge struct {
|
||||
ID string `json:"id"`
|
||||
AccountID string `json:"accountID"`
|
||||
AuthzID string `json:"authzID"`
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status"`
|
||||
Token string `json:"token"`
|
||||
Value string `json:"value"`
|
||||
Validated time.Time `json:"validated"`
|
||||
Created time.Time `json:"created"`
|
||||
Error *AError `json:"error"`
|
||||
}
|
||||
|
||||
func newBaseChallenge(accountID, authzID string) (*baseChallenge, error) {
|
||||
id, err := randID()
|
||||
if err != nil {
|
||||
return nil, Wrap(err, "error generating random id for ACME challenge")
|
||||
}
|
||||
token, err := randID()
|
||||
if err != nil {
|
||||
return nil, Wrap(err, "error generating token for ACME challenge")
|
||||
}
|
||||
|
||||
return &baseChallenge{
|
||||
ID: id,
|
||||
AccountID: accountID,
|
||||
AuthzID: authzID,
|
||||
Status: StatusPending,
|
||||
Token: token,
|
||||
Created: clock.Now(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// getID returns the id of the baseChallenge.
|
||||
func (bc *baseChallenge) getID() string {
|
||||
return bc.ID
|
||||
}
|
||||
|
||||
// getAuthzID returns the authz ID of the baseChallenge.
|
||||
func (bc *baseChallenge) getAuthzID() string {
|
||||
return bc.AuthzID
|
||||
}
|
||||
|
||||
// getAccountID returns the account id of the baseChallenge.
|
||||
func (bc *baseChallenge) getAccountID() string {
|
||||
return bc.AccountID
|
||||
}
|
||||
|
||||
// getType returns the type of the baseChallenge.
|
||||
func (bc *baseChallenge) getType() string {
|
||||
return bc.Type
|
||||
}
|
||||
|
||||
// getValue returns the type of the baseChallenge.
|
||||
func (bc *baseChallenge) getValue() string {
|
||||
return bc.Value
|
||||
}
|
||||
|
||||
// getStatus returns the status of the baseChallenge.
|
||||
func (bc *baseChallenge) getStatus() string {
|
||||
return bc.Status
|
||||
}
|
||||
|
||||
// getToken returns the token of the baseChallenge.
|
||||
func (bc *baseChallenge) getToken() string {
|
||||
return bc.Token
|
||||
}
|
||||
|
||||
// getValidated returns the validated time of the baseChallenge.
|
||||
func (bc *baseChallenge) getValidated() time.Time {
|
||||
return bc.Validated
|
||||
}
|
||||
|
||||
// getCreated returns the created time of the baseChallenge.
|
||||
func (bc *baseChallenge) getCreated() time.Time {
|
||||
return bc.Created
|
||||
}
|
||||
|
||||
// getCreated returns the created time of the baseChallenge.
|
||||
func (bc *baseChallenge) getError() *AError {
|
||||
return bc.Error
|
||||
}
|
||||
|
||||
// toACME converts the internal Challenge type into the public acmeChallenge
|
||||
// type for presentation in the ACME protocol.
|
||||
func (bc *baseChallenge) toACME(ctx context.Context, db nosql.DB, dir *directory) (*Challenge, error) {
|
||||
ac := &Challenge{
|
||||
Type: bc.getType(),
|
||||
Status: bc.getStatus(),
|
||||
Token: bc.getToken(),
|
||||
URL: dir.getLink(ctx, ChallengeLink, true, bc.getID()),
|
||||
ID: bc.getID(),
|
||||
AuthzID: bc.getAuthzID(),
|
||||
}
|
||||
if !bc.Validated.IsZero() {
|
||||
ac.Validated = bc.Validated.Format(time.RFC3339)
|
||||
}
|
||||
if bc.Error != nil {
|
||||
ac.Error = bc.Error
|
||||
}
|
||||
return ac, nil
|
||||
}
|
||||
|
||||
// save writes the challenge to disk. For new challenges 'old' should be nil,
|
||||
// otherwise 'old' should be a pointer to the acme challenge as it was at the
|
||||
// start of the request. This method will fail if the value currently found
|
||||
// in the bucket/row does not match the value of 'old'.
|
||||
func (bc *baseChallenge) save(db nosql.DB, old challenge) error {
|
||||
newB, err := json.Marshal(bc)
|
||||
if err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err,
|
||||
"error marshaling new acme challenge"))
|
||||
}
|
||||
var oldB []byte
|
||||
if old == nil {
|
||||
oldB = nil
|
||||
} else {
|
||||
oldB, err = json.Marshal(old)
|
||||
if err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err,
|
||||
"error marshaling old acme challenge"))
|
||||
}
|
||||
}
|
||||
|
||||
_, swapped, err := db.CmpAndSwap(challengeTable, []byte(bc.ID), oldB, newB)
|
||||
switch {
|
||||
case err != nil:
|
||||
return ServerInternalErr(errors.Wrap(err, "error saving acme challenge"))
|
||||
case !swapped:
|
||||
return ServerInternalErr(errors.New("error saving acme challenge; " +
|
||||
"acme challenge has changed since last read"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (bc *baseChallenge) clone() *baseChallenge {
|
||||
u := *bc
|
||||
return &u
|
||||
}
|
||||
|
||||
func (bc *baseChallenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
|
||||
return nil, ServerInternalErr(errors.New("unimplemented"))
|
||||
}
|
||||
|
||||
func (bc *baseChallenge) storeError(db nosql.DB, err *Error) error {
|
||||
clone := bc.clone()
|
||||
clone.Error = err.ToACME()
|
||||
if err := clone.save(db, bc); err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err, "failure saving error to acme challenge"))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// unmarshalChallenge unmarshals a challenge type into the correct sub-type.
|
||||
func unmarshalChallenge(data []byte) (challenge, error) {
|
||||
var getType struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &getType); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling challenge type"))
|
||||
}
|
||||
|
||||
switch getType.Type {
|
||||
case "dns-01":
|
||||
var bc baseChallenge
|
||||
if err := json.Unmarshal(data, &bc); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
|
||||
"challenge type into dns01Challenge"))
|
||||
}
|
||||
return &dns01Challenge{&bc}, nil
|
||||
case "http-01":
|
||||
var bc baseChallenge
|
||||
if err := json.Unmarshal(data, &bc); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
|
||||
"challenge type into http01Challenge"))
|
||||
}
|
||||
return &http01Challenge{&bc}, nil
|
||||
case "tls-alpn-01":
|
||||
var bc baseChallenge
|
||||
if err := json.Unmarshal(data, &bc); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
|
||||
"challenge type into tlsALPN01Challenge"))
|
||||
}
|
||||
return &tlsALPN01Challenge{&bc}, nil
|
||||
default:
|
||||
return nil, ServerInternalErr(errors.Errorf("unexpected challenge type %s", getType.Type))
|
||||
}
|
||||
}
|
||||
|
||||
// http01Challenge represents an http-01 acme challenge.
|
||||
type http01Challenge struct {
|
||||
*baseChallenge
|
||||
}
|
||||
|
||||
// newHTTP01Challenge returns a new acme http-01 challenge.
|
||||
func newHTTP01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
|
||||
bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bc.Type = "http-01"
|
||||
bc.Value = ops.Identifier.Value
|
||||
|
||||
hc := &http01Challenge{bc}
|
||||
if err := hc.save(db, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return hc, nil
|
||||
}
|
||||
|
||||
// Validate attempts to validate the challenge. If the challenge has been
|
||||
// satisfactorily validated, the 'status' and 'validated' attributes are
|
||||
// updated.
|
||||
func (hc *http01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
|
||||
// If already valid or invalid then return without performing validation.
|
||||
if hc.getStatus() == StatusValid || hc.getStatus() == StatusInvalid {
|
||||
return hc, nil
|
||||
}
|
||||
url := fmt.Sprintf("http://%s/.well-known/acme-challenge/%s", hc.Value, hc.Token)
|
||||
|
||||
resp, err := vo.httpGet(url)
|
||||
if err != nil {
|
||||
if err = hc.storeError(db, ConnectionErr(errors.Wrapf(err,
|
||||
"error doing http GET for url %s", url))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return hc, nil
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
if err = hc.storeError(db,
|
||||
ConnectionErr(errors.Errorf("error doing http GET for url %s with status code %d",
|
||||
url, resp.StatusCode))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return hc, nil
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error reading "+
|
||||
"response body for url %s", url))
|
||||
}
|
||||
keyAuth := strings.Trim(string(body), "\r\n")
|
||||
|
||||
expected, err := KeyAuthorization(hc.Token, jwk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if keyAuth != expected {
|
||||
if err = hc.storeError(db,
|
||||
RejectedIdentifierErr(errors.Errorf("keyAuthorization does not match; "+
|
||||
"expected %s, but got %s", expected, keyAuth))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return hc, nil
|
||||
}
|
||||
|
||||
// Update and store the challenge.
|
||||
upd := &http01Challenge{hc.baseChallenge.clone()}
|
||||
upd.Status = StatusValid
|
||||
upd.Error = nil
|
||||
upd.Validated = clock.Now()
|
||||
|
||||
if err := upd.save(db, hc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return upd, nil
|
||||
}
|
||||
|
||||
type tlsALPN01Challenge struct {
|
||||
*baseChallenge
|
||||
}
|
||||
|
||||
// newTLSALPN01Challenge returns a new acme tls-alpn-01 challenge.
|
||||
func newTLSALPN01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
|
||||
bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bc.Type = "tls-alpn-01"
|
||||
bc.Value = ops.Identifier.Value
|
||||
|
||||
hc := &tlsALPN01Challenge{bc}
|
||||
if err := hc.save(db, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return hc, nil
|
||||
}
|
||||
|
||||
func (tc *tlsALPN01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
|
||||
// If already valid or invalid then return without performing validation.
|
||||
if tc.getStatus() == StatusValid || tc.getStatus() == StatusInvalid {
|
||||
return tc, nil
|
||||
}
|
||||
|
||||
config := &tls.Config{
|
||||
NextProtos: []string{"acme-tls/1"},
|
||||
ServerName: tc.Value,
|
||||
InsecureSkipVerify: true, // we expect a self-signed challenge certificate
|
||||
}
|
||||
|
||||
hostPort := net.JoinHostPort(tc.Value, "443")
|
||||
|
||||
conn, err := vo.tlsDial("tcp", hostPort, config)
|
||||
if err != nil {
|
||||
if err = tc.storeError(db,
|
||||
ConnectionErr(errors.Wrapf(err, "error doing TLS dial for %s", hostPort))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tc, nil
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
cs := conn.ConnectionState()
|
||||
certs := cs.PeerCertificates
|
||||
|
||||
if len(certs) == 0 {
|
||||
if err = tc.storeError(db,
|
||||
RejectedIdentifierErr(errors.Errorf("%s challenge for %s resulted in no certificates",
|
||||
tc.Type, tc.Value))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tc, nil
|
||||
}
|
||||
|
||||
if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != "acme-tls/1" {
|
||||
if err = tc.storeError(db,
|
||||
RejectedIdentifierErr(errors.Errorf("cannot negotiate ALPN acme-tls/1 protocol for "+
|
||||
"tls-alpn-01 challenge"))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tc, nil
|
||||
}
|
||||
|
||||
leafCert := certs[0]
|
||||
|
||||
if len(leafCert.DNSNames) != 1 || !strings.EqualFold(leafCert.DNSNames[0], tc.Value) {
|
||||
if err = tc.storeError(db,
|
||||
RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
|
||||
"leaf certificate must contain a single DNS name, %v", tc.Value))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tc, nil
|
||||
}
|
||||
|
||||
idPeAcmeIdentifier := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
|
||||
idPeAcmeIdentifierV1Obsolete := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
|
||||
foundIDPeAcmeIdentifierV1Obsolete := false
|
||||
|
||||
keyAuth, err := KeyAuthorization(tc.Token, jwk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
|
||||
|
||||
for _, ext := range leafCert.Extensions {
|
||||
if idPeAcmeIdentifier.Equal(ext.Id) {
|
||||
if !ext.Critical {
|
||||
if err = tc.storeError(db,
|
||||
RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
|
||||
"acmeValidationV1 extension not critical"))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tc, nil
|
||||
}
|
||||
|
||||
var extValue []byte
|
||||
rest, err := asn1.Unmarshal(ext.Value, &extValue)
|
||||
|
||||
if err != nil || len(rest) > 0 || len(hashedKeyAuth) != len(extValue) {
|
||||
if err = tc.storeError(db,
|
||||
RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
|
||||
"malformed acmeValidationV1 extension value"))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tc, nil
|
||||
}
|
||||
|
||||
if subtle.ConstantTimeCompare(hashedKeyAuth[:], extValue) != 1 {
|
||||
if err = tc.storeError(db,
|
||||
RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
|
||||
"expected acmeValidationV1 extension value %s for this challenge but got %s",
|
||||
hex.EncodeToString(hashedKeyAuth[:]), hex.EncodeToString(extValue)))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tc, nil
|
||||
}
|
||||
|
||||
upd := &tlsALPN01Challenge{tc.baseChallenge.clone()}
|
||||
upd.Status = StatusValid
|
||||
upd.Error = nil
|
||||
upd.Validated = clock.Now()
|
||||
|
||||
if err := upd.save(db, tc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return upd, nil
|
||||
}
|
||||
|
||||
if idPeAcmeIdentifierV1Obsolete.Equal(ext.Id) {
|
||||
foundIDPeAcmeIdentifierV1Obsolete = true
|
||||
}
|
||||
}
|
||||
|
||||
if foundIDPeAcmeIdentifierV1Obsolete {
|
||||
if err = tc.storeError(db,
|
||||
RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
|
||||
"obsolete id-pe-acmeIdentifier in acmeValidationV1 extension"))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tc, nil
|
||||
}
|
||||
|
||||
if err = tc.storeError(db,
|
||||
RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
|
||||
"missing acmeValidationV1 extension"))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return tc, nil
|
||||
}
|
||||
|
||||
// dns01Challenge represents an dns-01 acme challenge.
|
||||
type dns01Challenge struct {
|
||||
*baseChallenge
|
||||
}
|
||||
|
||||
// newDNS01Challenge returns a new acme dns-01 challenge.
|
||||
func newDNS01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
|
||||
bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bc.Type = "dns-01"
|
||||
bc.Value = ops.Identifier.Value
|
||||
|
||||
dc := &dns01Challenge{bc}
|
||||
if err := dc.save(db, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dc, nil
|
||||
}
|
||||
|
||||
// KeyAuthorization creates the ACME key authorization value from a token
|
||||
// and a jwk.
|
||||
func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
|
||||
thumbprint, err := jwk.Thumbprint(crypto.SHA256)
|
||||
if err != nil {
|
||||
return "", ServerInternalErr(errors.Wrap(err, "error generating JWK thumbprint"))
|
||||
}
|
||||
encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
|
||||
return fmt.Sprintf("%s.%s", token, encPrint), nil
|
||||
}
|
||||
|
||||
// validate attempts to validate the challenge. If the challenge has been
|
||||
// satisfactorily validated, the 'status' and 'validated' attributes are
|
||||
// updated.
|
||||
func (dc *dns01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
|
||||
// If already valid or invalid then return without performing validation.
|
||||
if dc.getStatus() == StatusValid || dc.getStatus() == StatusInvalid {
|
||||
return dc, nil
|
||||
}
|
||||
|
||||
// Normalize domain for wildcard DNS names
|
||||
// This is done to avoid making TXT lookups for domains like
|
||||
// _acme-challenge.*.example.com
|
||||
// Instead perform txt lookup for _acme-challenge.example.com
|
||||
domain := strings.TrimPrefix(dc.Value, "*.")
|
||||
|
||||
txtRecords, err := vo.lookupTxt("_acme-challenge." + domain)
|
||||
if err != nil {
|
||||
if err = dc.storeError(db,
|
||||
DNSErr(errors.Wrapf(err, "error looking up TXT "+
|
||||
"records for domain %s", domain))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dc, nil
|
||||
}
|
||||
|
||||
expectedKeyAuth, err := KeyAuthorization(dc.Token, jwk)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
h := sha256.Sum256([]byte(expectedKeyAuth))
|
||||
expected := base64.RawURLEncoding.EncodeToString(h[:])
|
||||
var found bool
|
||||
for _, r := range txtRecords {
|
||||
if r == expected {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
if err = dc.storeError(db,
|
||||
RejectedIdentifierErr(errors.Errorf("keyAuthorization "+
|
||||
"does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return dc, nil
|
||||
}
|
||||
|
||||
// Update and store the challenge.
|
||||
upd := &dns01Challenge{dc.baseChallenge.clone()}
|
||||
upd.Status = StatusValid
|
||||
upd.Error = nil
|
||||
upd.Validated = time.Now().UTC()
|
||||
|
||||
if err := upd.save(db, dc); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return upd, nil
|
||||
}
|
||||
|
||||
// getChallenge retrieves and unmarshals an ACME challenge type from the database.
|
||||
func getChallenge(db nosql.DB, id string) (challenge, error) {
|
||||
b, err := db.Get(challengeTable, []byte(id))
|
||||
if nosql.IsErrNotFound(err) {
|
||||
return nil, MalformedErr(errors.Wrapf(err, "challenge %s not found", id))
|
||||
} else if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error loading challenge %s", id))
|
||||
}
|
||||
ch, err := unmarshalChallenge(b)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ch, nil
|
||||
}
|
|
@ -4,28 +4,28 @@ import "context"
|
|||
|
||||
// DB is the DB interface expected by the step-ca ACME API.
|
||||
type DB interface {
|
||||
CreateAccount(ctx context.Context, acc *Account) (*Account, error)
|
||||
GetAccount(ctx context.Context, id string) (*Account, error)
|
||||
GetAccountByKeyID(ctx context.Context) (*Account, error)
|
||||
UpdateAccount(ctx context.Context, acc *Account) error
|
||||
CreateAccount(ctx context.Context, acc *types.Account) (*types.Account, error)
|
||||
GetAccount(ctx context.Context, id string) (*types.Account, error)
|
||||
GetAccountByKeyID(ctx context.Context, kid string) (*types.Account, error)
|
||||
UpdateAccount(ctx context.Context, acc *types.Account) error
|
||||
|
||||
CreateNonce(ctx context.Context) (Nonce, error)
|
||||
DeleteNonce(ctx context.Context, nonce Nonce) error
|
||||
CreateNonce(ctx context.Context) (types.Nonce, error)
|
||||
DeleteNonce(ctx context.Context, nonce types.Nonce) error
|
||||
|
||||
CreateAuthorization(ctx context.Context, authz *Authorization) error
|
||||
GetAuthorization(ctx context.Context, id string) (*Authorization, error)
|
||||
UpdateAuthorization(ctx context.Context, authz *Authorization) error
|
||||
CreateAuthorization(ctx context.Context, authz *types.Authorization) error
|
||||
GetAuthorization(ctx context.Context, id string) (*types.Authorization, error)
|
||||
UpdateAuthorization(ctx context.Context, authz *types.Authorization) error
|
||||
|
||||
CreateCertificate(ctx context.Context, cert *Certificate) error
|
||||
GetCertificate(ctx context.Context, id string) (*Certificate, error)
|
||||
CreateCertificate(ctx context.Context, cert *types.Certificate) error
|
||||
GetCertificate(ctx context.Context, id string) (*types.Certificate, error)
|
||||
|
||||
CreateChallenge(ctx context.Context, ch *Challenge) error
|
||||
GetChallenge(ctx context.Context, id string) (*Challenge, error)
|
||||
UpdateChallenge(ctx context.Context, ch *Challenge) error
|
||||
CreateChallenge(ctx context.Context, ch *types.Challenge) error
|
||||
GetChallenge(ctx context.Context, id, authzID string) (*types.Challenge, error)
|
||||
UpdateChallenge(ctx context.Context, ch *types.Challenge) error
|
||||
|
||||
CreateOrder(ctx context.Context, o *Order) error
|
||||
CreateOrder(ctx context.Context, o *types.Order) error
|
||||
DeleteOrder(ctx context.Context, id string) error
|
||||
GetOrder(ctx context.Context, id string) (*Order, error)
|
||||
GetOrder(ctx context.Context, id string) (*types.Order, error)
|
||||
GetOrdersByAccountID(ctx context.Context, accountID string) error
|
||||
UpdateOrder(ctx context.Context, o *Order) error
|
||||
UpdateOrder(ctx context.Context, o *types.Order) error
|
||||
}
|
||||
|
|
|
@ -20,7 +20,12 @@ type dbAccount struct {
|
|||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
func (db *DB) saveAccount(nu *dbAccount, old *dbAccount) error {
|
||||
func (dba *dbAccount) clone() *dbAccount {
|
||||
nu := *dba
|
||||
return &nu
|
||||
}
|
||||
|
||||
func (db *DB) saveDBAccount(nu *dbAccount, old *dbAccount) error {
|
||||
var (
|
||||
err error
|
||||
oldB []byte
|
||||
|
@ -51,7 +56,7 @@ func (db *DB) saveAccount(nu *dbAccount, old *dbAccount) error {
|
|||
}
|
||||
|
||||
// CreateAccount imlements the AcmeDB.CreateAccount interface.
|
||||
func (db *DB) CreateAccount(ctx context.Context, acc *Account) error {
|
||||
func (db *DB) CreateAccount(ctx context.Context, acc *types.Account) error {
|
||||
id, err := randID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -79,7 +84,7 @@ func (db *DB) CreateAccount(ctx context.Context, acc *Account) error {
|
|||
case !swapped:
|
||||
return ServerInternalErr(errors.Errorf("key-id to account-id index already exists"))
|
||||
default:
|
||||
if err = db.saveAccount(dba, nil); err != nil {
|
||||
if err = db.saveDBAccount(dba, nil); err != nil {
|
||||
db.db.Del(accountByKeyIDTable, kidB)
|
||||
return err
|
||||
}
|
||||
|
@ -87,46 +92,49 @@ func (db *DB) CreateAccount(ctx context.Context, acc *Account) error {
|
|||
}
|
||||
}
|
||||
|
||||
// GetAccount retrieves an ACME account by ID.
|
||||
func (db *DB) GetAccount(ctx context.Context, id string) (*types.Account, error) {
|
||||
|
||||
return &types.Account{
|
||||
Status: dbacc.Status,
|
||||
Contact: dbacc.Contact,
|
||||
Orders: dir.getLink(ctx, OrdersByAccountLink, true, a.ID),
|
||||
Key: dbacc.Key,
|
||||
ID: dbacc.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetAccountByKeyID retrieves an ACME account by KeyID (thumbprint of the Account Key -- JWK).
|
||||
func (db *DB) GetAccountByKeyID(ctx context.Context, kid string) (*types.Account, error) {
|
||||
id, err := db.getAccountIDByKeyID(kid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return db.GetAccount(ctx, id)
|
||||
}
|
||||
|
||||
// UpdateAccount imlements the AcmeDB.UpdateAccount interface.
|
||||
func (db *DB) UpdateAccount(ctx context.Context, acc *Account) error {
|
||||
kid, err := keyToID(dba.Key)
|
||||
func (db *DB) UpdateAccount(ctx context.Context, acc *types.Account) error {
|
||||
kid := "from-context"
|
||||
|
||||
old, err := db.getDBAccountByKeyID(ctx, kid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dba, err := db.db.getAccountByKeyID(ctx, kid)
|
||||
|
||||
newdba := *dba
|
||||
newdba.Contact = acc.contact
|
||||
newdba.Status = acc.Status
|
||||
nu := old.clone()
|
||||
nu.Contact = acc.contact
|
||||
nu.Status = acc.Status
|
||||
|
||||
// If the status has changed to 'deactivated', then set deactivatedAt timestamp.
|
||||
if acc.Status == types.StatusDeactivated && dba.Status != types.Status.Deactivated {
|
||||
newdba.Deactivated = clock.Now()
|
||||
if acc.Status == types.StatusDeactivated && old.Status != types.Status.Deactivated {
|
||||
nu.Deactivated = clock.Now()
|
||||
}
|
||||
|
||||
return db.saveAccount(newdba, dba)
|
||||
return db.saveDBAccount(newdba, dba)
|
||||
}
|
||||
|
||||
// getAccountByID retrieves the account with the given ID.
|
||||
func (db *DB) getAccountByID(ctx context.Context, id string) (*dbAccount, error) {
|
||||
ab, err := db.db.Get(accountTable, []byte(id))
|
||||
if err != nil {
|
||||
if nosqlDB.IsErrNotFound(err) {
|
||||
return nil, MalformedErr(errors.Wrapf(err, "account %s not found", id))
|
||||
}
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error loading account %s", id))
|
||||
}
|
||||
|
||||
a := new(account)
|
||||
if err = json.Unmarshal(ab, a); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling account"))
|
||||
}
|
||||
return a, nil
|
||||
}
|
||||
|
||||
// getAccountByKeyID retrieves Id associated with the given Kid.
|
||||
func (db *DB) getAccountByKeyID(ctx context.Context, kid string) (*dbAccount, error) {
|
||||
func (db *DB) getAccountIDByKeyID(ctx context.Context, kid string) (string, error) {
|
||||
id, err := db.db.Get(accountByKeyIDTable, []byte(kid))
|
||||
if err != nil {
|
||||
if nosqlDB.IsErrNotFound(err) {
|
||||
|
@ -134,5 +142,26 @@ func (db *DB) getAccountByKeyID(ctx context.Context, kid string) (*dbAccount, er
|
|||
}
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error loading key-account index"))
|
||||
}
|
||||
return getAccountByID(db, string(id))
|
||||
return string(id), nil
|
||||
}
|
||||
|
||||
// getDBAccountByKeyID retrieves Id associated with the given Kid.
|
||||
func (db *DB) getDBAccountByKeyID(ctx context.Context, kid string) (*dbAccount, error) {
|
||||
id, err := db.getAccountIDByKeyID(ctx, kid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := db.db.Get(accountTable, []byte(id))
|
||||
if err != nil {
|
||||
if nosqlDB.IsErrNotFound(err) {
|
||||
return nil, MalformedErr(errors.Wrapf(err, "account %s not found", id))
|
||||
}
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error loading account %s", id))
|
||||
}
|
||||
|
||||
dbacc := new(account)
|
||||
if err = json.Unmarshal(data, dbacc); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling account"))
|
||||
}
|
||||
return dbacc, nil
|
||||
}
|
||||
|
|
|
@ -0,0 +1,216 @@
|
|||
package nosql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/smallstep/nosql"
|
||||
)
|
||||
|
||||
var defaultExpiryDuration = time.Hour * 24
|
||||
|
||||
// dbAuthz is the base authz type that others build from.
|
||||
type dbAuthz struct {
|
||||
ID string `json:"id"`
|
||||
AccountID string `json:"accountID"`
|
||||
Identifier Identifier `json:"identifier"`
|
||||
Status string `json:"status"`
|
||||
Expires time.Time `json:"expires"`
|
||||
Challenges []string `json:"challenges"`
|
||||
Wildcard bool `json:"wildcard"`
|
||||
Created time.Time `json:"created"`
|
||||
Error *Error `json:"error"`
|
||||
}
|
||||
|
||||
func (ba *dbAuthz) clone() *dbAuthz {
|
||||
u := *ba
|
||||
return &u
|
||||
}
|
||||
|
||||
func (db *DB) saveDBAuthz(ctx context.Context, nu *authz, old *dbAuthz) error {
|
||||
var (
|
||||
err error
|
||||
oldB, newB []byte
|
||||
)
|
||||
|
||||
if old == nil {
|
||||
oldB = nil
|
||||
} else {
|
||||
if oldB, err = json.Marshal(old); err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err, "error marshaling old authz"))
|
||||
}
|
||||
}
|
||||
if newB, err = json.Marshal(nu); err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err, "error marshaling new authz"))
|
||||
}
|
||||
_, swapped, err := db.CmpAndSwap(authzTable, []byte(ba.ID), oldB, newB)
|
||||
switch {
|
||||
case err != nil:
|
||||
return ServerInternalErr(errors.Wrapf(err, "error storing authz"))
|
||||
case !swapped:
|
||||
return ServerInternalErr(errors.Errorf("error storing authz; " +
|
||||
"value has changed since last read"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// getDBAuthz retrieves and unmarshals a database representation of the
|
||||
// ACME Authorization type.
|
||||
func (db *DB) getDBAuthz(ctx context.Context, id string) (*dbAuthz, error) {
|
||||
data, err := db.db.Get(authzTable, []byte(id))
|
||||
if nosql.IsErrNotFound(err) {
|
||||
return nil, MalformedErr(errors.Wrapf(err, "authz %s not found", id))
|
||||
} else if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error loading authz %s", id))
|
||||
}
|
||||
|
||||
var dbaz dbAuthz
|
||||
if err = json.Unmarshal(data, &dbaz); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling authz type into dbAuthz"))
|
||||
}
|
||||
return &dbaz
|
||||
}
|
||||
|
||||
// GetAuthorization retrieves and unmarshals an ACME authz type from the database.
|
||||
// Implements acme.DB GetAuthorization interface.
|
||||
func (db *DB) GetAuthorization(ctx context.Context, id string) (*types.Authorization, error) {
|
||||
dbaz, err := getDBAuthz(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var chs = make([]*Challenge, len(ba.Challenges))
|
||||
for i, chID := range dbaz.Challenges {
|
||||
chs[i], err = db.GetChallenge(ctx, chID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &types.Authorization{
|
||||
Identifier: dbaz.Identifier,
|
||||
Status: dbaz.Status,
|
||||
Challenges: chs,
|
||||
Wildcard: dbaz.Wildcard,
|
||||
Expires: dbaz.Expires.Format(time.RFC3339),
|
||||
ID: dbaz.ID,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreateAuthorization creates an entry in the database for the Authorization.
|
||||
// Implements the acme.DB.CreateAuthorization interface.
|
||||
func (db *DB) CreateAuthorization(ctx context.Context, az *types.Authorization) error {
|
||||
if len(authz.AccountID) == 0 {
|
||||
return ServerInternalErr(errors.New("AccountID cannot be empty"))
|
||||
}
|
||||
az.ID, err = randID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
now := clock.Now()
|
||||
dbaz := &dbAuthz{
|
||||
ID: az.ID,
|
||||
AccountID: az.AccountId,
|
||||
Status: types.StatusPending,
|
||||
Created: now,
|
||||
Expires: now.Add(defaultExpiryDuration),
|
||||
Identifier: az.Identifier,
|
||||
}
|
||||
|
||||
if strings.HasPrefix(az.Identifier.Value, "*.") {
|
||||
dbaz.Wildcard = true
|
||||
dbaz.Identifier = Identifier{
|
||||
Value: strings.TrimPrefix(identifier.Value, "*."),
|
||||
Type: identifier.Type,
|
||||
}
|
||||
}
|
||||
|
||||
chIDs := []string{}
|
||||
chTypes := []string{"dns-01"}
|
||||
// HTTP and TLS challenges can only be used for identifiers without wildcards.
|
||||
if !dbaz.Wildcard {
|
||||
chTypes = append(chTypes, []string{"http-01", "tls-alpn-01"}...)
|
||||
}
|
||||
|
||||
for _, typ := range chTypes {
|
||||
ch, err := db.CreateChallenge(ctx, &types.Challenge{
|
||||
AccountID: az.AccountID,
|
||||
AuthzID: az.ID,
|
||||
Value: az.Identifier.Value,
|
||||
Type: typ,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, Wrapf(err, "error creating '%s' challenge", typ)
|
||||
}
|
||||
|
||||
chIDs = append(chIDs, ch.ID)
|
||||
}
|
||||
dbaz.Challenges = chIDs
|
||||
|
||||
return db.saveDBAuthz(ctx, dbaz, nil)
|
||||
}
|
||||
|
||||
// UpdateAuthorization saves an updated ACME Authorization to the database.
|
||||
func (db *DB) UpdateAuthorization(ctx context.Context, az *types.Authorization) error {
|
||||
old, err := db.getDBAuthz(ctx, az.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
nu := old.clone()
|
||||
|
||||
nu.Status = az.Status
|
||||
nu.Error = az.Error
|
||||
return db.saveDBAuthz(ctx, nu, old)
|
||||
}
|
||||
|
||||
/*
|
||||
// updateStatus attempts to update the status on a dbAuthz and stores the
|
||||
// updating object if necessary.
|
||||
func (ba *dbAuthz) updateStatus(db nosql.DB) (authz, error) {
|
||||
newAuthz := ba.clone()
|
||||
|
||||
now := time.Now().UTC()
|
||||
switch ba.Status {
|
||||
case StatusInvalid:
|
||||
return ba.parent(), nil
|
||||
case StatusValid:
|
||||
return ba.parent(), nil
|
||||
case StatusPending:
|
||||
// check expiry
|
||||
if now.After(ba.Expires) {
|
||||
newAuthz.Status = StatusInvalid
|
||||
newAuthz.Error = MalformedErr(errors.New("authz has expired"))
|
||||
break
|
||||
}
|
||||
|
||||
var isValid = false
|
||||
for _, chID := range ba.Challenges {
|
||||
ch, err := getChallenge(db, chID)
|
||||
if err != nil {
|
||||
return ba, err
|
||||
}
|
||||
if ch.getStatus() == StatusValid {
|
||||
isValid = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !isValid {
|
||||
return ba.parent(), nil
|
||||
}
|
||||
newAuthz.Status = StatusValid
|
||||
newAuthz.Error = nil
|
||||
default:
|
||||
return nil, ServerInternalErr(errors.Errorf("unrecognized authz status: %s", ba.Status))
|
||||
}
|
||||
|
||||
if err := newAuthz.save(db, ba); err != nil {
|
||||
return ba, err
|
||||
}
|
||||
return newAuthz.parent(), nil
|
||||
}
|
||||
*/
|
|
@ -0,0 +1,528 @@
|
|||
package nosql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/smallstep/nosql"
|
||||
)
|
||||
|
||||
// ChallengeOptions is the type used to created a new Challenge.
|
||||
type ChallengeOptions struct {
|
||||
AccountID string
|
||||
AuthzID string
|
||||
Identifier Identifier
|
||||
}
|
||||
|
||||
// dbChallenge is the base Challenge type that others build from.
|
||||
type dbChallenge struct {
|
||||
ID string `json:"id"`
|
||||
AccountID string `json:"accountID"`
|
||||
AuthzID string `json:"authzID"`
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status"`
|
||||
Token string `json:"token"`
|
||||
Value string `json:"value"`
|
||||
Validated time.Time `json:"validated"`
|
||||
Created time.Time `json:"created"`
|
||||
Error *AError `json:"error"`
|
||||
}
|
||||
|
||||
func (dbc *dbChallenge) clone() *dbChallenge {
|
||||
u := *bc
|
||||
return &u
|
||||
}
|
||||
|
||||
// save writes the challenge to disk. For new challenges 'old' should be nil,
|
||||
// otherwise 'old' should be a pointer to the acme challenge as it was at the
|
||||
// start of the request. This method will fail if the value currently found
|
||||
// in the bucket/row does not match the value of 'old'.
|
||||
func (db *DB) saveDBChallenge(ctx context.Context, nu challenge, old challenge) error {
|
||||
newB, err := json.Marshal(nu)
|
||||
if err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err,
|
||||
"error marshaling new acme challenge"))
|
||||
}
|
||||
var oldB []byte
|
||||
if old == nil {
|
||||
oldB = nil
|
||||
} else {
|
||||
oldB, err = json.Marshal(old)
|
||||
if err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err,
|
||||
"error marshaling old acme challenge"))
|
||||
}
|
||||
}
|
||||
|
||||
_, swapped, err := db.CmpAndSwap(challengeTable, []byte(bc.ID), oldB, newB)
|
||||
switch {
|
||||
case err != nil:
|
||||
return ServerInternalErr(errors.Wrap(err, "error saving acme challenge"))
|
||||
case !swapped:
|
||||
return ServerInternalErr(errors.New("error saving acme challenge; " +
|
||||
"acme challenge has changed since last read"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (db *DB) getDBChallenge(ctx context.Context, id string) (*dbChallenge, error) {
|
||||
data, err := db.db.Get(challengeTable, []byte(id))
|
||||
if nosql.IsErrNotFound(err) {
|
||||
return nil, MalformedErr(errors.Wrapf(err, "challenge %s not found", id))
|
||||
} else if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error loading challenge %s", id))
|
||||
}
|
||||
|
||||
dbch := new(baseChallenge)
|
||||
if err := json.Unmarshal(data, dbch); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
|
||||
"challenge type into dbChallenge"))
|
||||
}
|
||||
return dbch
|
||||
}
|
||||
|
||||
// CreateChallenge creates a new ACME challenge data structure in the database.
|
||||
// Implements acme.DB.CreateChallenge interface.
|
||||
func (db *DB) CreateChallenge(ctx context.context, ch *types.Challenge) error {
|
||||
if len(ch.AuthzID) == 0 {
|
||||
return ServerInternalError(errors.New("AuthzID cannot be empty"))
|
||||
}
|
||||
if len(ch.AccountID) == 0 {
|
||||
return ServerInternalError(errors.New("AccountID cannot be empty"))
|
||||
}
|
||||
if len(ch.Value) == 0 {
|
||||
return ServerInternalError(errors.New("AccountID cannot be empty"))
|
||||
}
|
||||
// TODO: verify that challenge type is set and is one of expected types.
|
||||
if len(ch.Type) == 0 {
|
||||
return ServerInternalError(errors.New("Type cannot be empty"))
|
||||
}
|
||||
|
||||
ch.ID, err = randID()
|
||||
if err != nil {
|
||||
return nil, Wrap(err, "error generating random id for ACME challenge")
|
||||
}
|
||||
ch.Token, err = randID()
|
||||
if err != nil {
|
||||
return nil, Wrap(err, "error generating token for ACME challenge")
|
||||
}
|
||||
|
||||
dbch := &dbChallenge{
|
||||
ID: ch.ID,
|
||||
AuthzID: ch.AuthzID,
|
||||
AccountID: ch.AccountID,
|
||||
Value: ch.Value,
|
||||
Status: types.StatusPending,
|
||||
Token: ch.Token,
|
||||
Created: clock.Now(),
|
||||
Type: ch.Type,
|
||||
}
|
||||
|
||||
return dbch.saveDBChallenge(ctx, dbch, nil)
|
||||
}
|
||||
|
||||
// GetChallenge retrieves and unmarshals an ACME challenge type from the database.
|
||||
// Implements the acme.DB GetChallenge interface.
|
||||
func (db *DB) GetChallenge(ctx context.Context, id, authzID string) (*types.Challenge, error) {
|
||||
dbch, err := db.getDBChallenge(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
ch := &Challenge{
|
||||
Type: dbch.Type,
|
||||
Status: dbch.Status,
|
||||
Token: dbch.Token,
|
||||
URL: dir.getLink(ctx, ChallengeLink, true, dbch.getID()),
|
||||
ID: dbch.ID,
|
||||
AuthzID: dbch.AuthzID(),
|
||||
Error: dbch.Error,
|
||||
}
|
||||
if !dbch.Validated.IsZero() {
|
||||
ac.Validated = dbch.Validated.Format(time.RFC3339)
|
||||
}
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// UpdateChallenge updates an ACME challenge type in the database.
|
||||
func (db *DB) UpdateChallenge(ctx context.Context, ch *types.Challenge) error {
|
||||
old, err := db.getDBChallenge(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
nu := old.clone()
|
||||
|
||||
// These should be the only values chaning in an Update request.
|
||||
nu.Status = ch.Status
|
||||
nu.Error = ch.Error
|
||||
if nu.Status == types.StatusValid {
|
||||
nu.Validated = clock.Now()
|
||||
}
|
||||
|
||||
return db.saveDBChallenge(ctx, nu, old)
|
||||
}
|
||||
|
||||
//// http01Challenge represents an http-01 acme challenge.
|
||||
//type http01Challenge struct {
|
||||
// *baseChallenge
|
||||
//}
|
||||
//
|
||||
//// newHTTP01Challenge returns a new acme http-01 challenge.
|
||||
//func newHTTP01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
|
||||
// bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// bc.Type = "http-01"
|
||||
// bc.Value = ops.Identifier.Value
|
||||
//
|
||||
// hc := &http01Challenge{bc}
|
||||
// if err := hc.save(db, nil); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return hc, nil
|
||||
//}
|
||||
//
|
||||
//// Validate attempts to validate the challenge. If the challenge has been
|
||||
//// satisfactorily validated, the 'status' and 'validated' attributes are
|
||||
//// updated.
|
||||
//func (hc *http01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
|
||||
// // If already valid or invalid then return without performing validation.
|
||||
// if hc.getStatus() == StatusValid || hc.getStatus() == StatusInvalid {
|
||||
// return hc, nil
|
||||
// }
|
||||
// url := fmt.Sprintf("http://%s/.well-known/acme-challenge/%s", hc.Value, hc.Token)
|
||||
//
|
||||
// resp, err := vo.httpGet(url)
|
||||
// if err != nil {
|
||||
// if err = hc.storeError(db, ConnectionErr(errors.Wrapf(err,
|
||||
// "error doing http GET for url %s", url))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return hc, nil
|
||||
// }
|
||||
// if resp.StatusCode >= 400 {
|
||||
// if err = hc.storeError(db,
|
||||
// ConnectionErr(errors.Errorf("error doing http GET for url %s with status code %d",
|
||||
// url, resp.StatusCode))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return hc, nil
|
||||
// }
|
||||
// defer resp.Body.Close()
|
||||
//
|
||||
// body, err := ioutil.ReadAll(resp.Body)
|
||||
// if err != nil {
|
||||
// return nil, ServerInternalErr(errors.Wrapf(err, "error reading "+
|
||||
// "response body for url %s", url))
|
||||
// }
|
||||
// keyAuth := strings.Trim(string(body), "\r\n")
|
||||
//
|
||||
// expected, err := KeyAuthorization(hc.Token, jwk)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// if keyAuth != expected {
|
||||
// if err = hc.storeError(db,
|
||||
// RejectedIdentifierErr(errors.Errorf("keyAuthorization does not match; "+
|
||||
// "expected %s, but got %s", expected, keyAuth))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return hc, nil
|
||||
// }
|
||||
//
|
||||
// // Update and store the challenge.
|
||||
// upd := &http01Challenge{hc.baseChallenge.clone()}
|
||||
// upd.Status = StatusValid
|
||||
// upd.Error = nil
|
||||
// upd.Validated = clock.Now()
|
||||
//
|
||||
// if err := upd.save(db, hc); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return upd, nil
|
||||
//}
|
||||
//
|
||||
//type tlsALPN01Challenge struct {
|
||||
// *baseChallenge
|
||||
//}
|
||||
//
|
||||
//// newTLSALPN01Challenge returns a new acme tls-alpn-01 challenge.
|
||||
//func newTLSALPN01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
|
||||
// bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// bc.Type = "tls-alpn-01"
|
||||
// bc.Value = ops.Identifier.Value
|
||||
//
|
||||
// hc := &tlsALPN01Challenge{bc}
|
||||
// if err := hc.save(db, nil); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return hc, nil
|
||||
//}
|
||||
//
|
||||
//func (tc *tlsALPN01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
|
||||
// // If already valid or invalid then return without performing validation.
|
||||
// if tc.getStatus() == StatusValid || tc.getStatus() == StatusInvalid {
|
||||
// return tc, nil
|
||||
// }
|
||||
//
|
||||
// config := &tls.Config{
|
||||
// NextProtos: []string{"acme-tls/1"},
|
||||
// ServerName: tc.Value,
|
||||
// InsecureSkipVerify: true, // we expect a self-signed challenge certificate
|
||||
// }
|
||||
//
|
||||
// hostPort := net.JoinHostPort(tc.Value, "443")
|
||||
//
|
||||
// conn, err := vo.tlsDial("tcp", hostPort, config)
|
||||
// if err != nil {
|
||||
// if err = tc.storeError(db,
|
||||
// ConnectionErr(errors.Wrapf(err, "error doing TLS dial for %s", hostPort))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return tc, nil
|
||||
// }
|
||||
// defer conn.Close()
|
||||
//
|
||||
// cs := conn.ConnectionState()
|
||||
// certs := cs.PeerCertificates
|
||||
//
|
||||
// if len(certs) == 0 {
|
||||
// if err = tc.storeError(db,
|
||||
// RejectedIdentifierErr(errors.Errorf("%s challenge for %s resulted in no certificates",
|
||||
// tc.Type, tc.Value))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return tc, nil
|
||||
// }
|
||||
//
|
||||
// if !cs.NegotiatedProtocolIsMutual || cs.NegotiatedProtocol != "acme-tls/1" {
|
||||
// if err = tc.storeError(db,
|
||||
// RejectedIdentifierErr(errors.Errorf("cannot negotiate ALPN acme-tls/1 protocol for "+
|
||||
// "tls-alpn-01 challenge"))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return tc, nil
|
||||
// }
|
||||
//
|
||||
// leafCert := certs[0]
|
||||
//
|
||||
// if len(leafCert.DNSNames) != 1 || !strings.EqualFold(leafCert.DNSNames[0], tc.Value) {
|
||||
// if err = tc.storeError(db,
|
||||
// RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
|
||||
// "leaf certificate must contain a single DNS name, %v", tc.Value))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return tc, nil
|
||||
// }
|
||||
//
|
||||
// idPeAcmeIdentifier := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 31}
|
||||
// idPeAcmeIdentifierV1Obsolete := asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 30, 1}
|
||||
// foundIDPeAcmeIdentifierV1Obsolete := false
|
||||
//
|
||||
// keyAuth, err := KeyAuthorization(tc.Token, jwk)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// hashedKeyAuth := sha256.Sum256([]byte(keyAuth))
|
||||
//
|
||||
// for _, ext := range leafCert.Extensions {
|
||||
// if idPeAcmeIdentifier.Equal(ext.Id) {
|
||||
// if !ext.Critical {
|
||||
// if err = tc.storeError(db,
|
||||
// RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
|
||||
// "acmeValidationV1 extension not critical"))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return tc, nil
|
||||
// }
|
||||
//
|
||||
// var extValue []byte
|
||||
// rest, err := asn1.Unmarshal(ext.Value, &extValue)
|
||||
//
|
||||
// if err != nil || len(rest) > 0 || len(hashedKeyAuth) != len(extValue) {
|
||||
// if err = tc.storeError(db,
|
||||
// RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
|
||||
// "malformed acmeValidationV1 extension value"))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return tc, nil
|
||||
// }
|
||||
//
|
||||
// if subtle.ConstantTimeCompare(hashedKeyAuth[:], extValue) != 1 {
|
||||
// if err = tc.storeError(db,
|
||||
// RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
|
||||
// "expected acmeValidationV1 extension value %s for this challenge but got %s",
|
||||
// hex.EncodeToString(hashedKeyAuth[:]), hex.EncodeToString(extValue)))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return tc, nil
|
||||
// }
|
||||
//
|
||||
// upd := &tlsALPN01Challenge{tc.baseChallenge.clone()}
|
||||
// upd.Status = StatusValid
|
||||
// upd.Error = nil
|
||||
// upd.Validated = clock.Now()
|
||||
//
|
||||
// if err := upd.save(db, tc); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return upd, nil
|
||||
// }
|
||||
//
|
||||
// if idPeAcmeIdentifierV1Obsolete.Equal(ext.Id) {
|
||||
// foundIDPeAcmeIdentifierV1Obsolete = true
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if foundIDPeAcmeIdentifierV1Obsolete {
|
||||
// if err = tc.storeError(db,
|
||||
// RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
|
||||
// "obsolete id-pe-acmeIdentifier in acmeValidationV1 extension"))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return tc, nil
|
||||
// }
|
||||
//
|
||||
// if err = tc.storeError(db,
|
||||
// RejectedIdentifierErr(errors.Errorf("incorrect certificate for tls-alpn-01 challenge: "+
|
||||
// "missing acmeValidationV1 extension"))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return tc, nil
|
||||
//}
|
||||
//
|
||||
//// dns01Challenge represents an dns-01 acme challenge.
|
||||
//type dns01Challenge struct {
|
||||
// *baseChallenge
|
||||
//}
|
||||
//
|
||||
//// newDNS01Challenge returns a new acme dns-01 challenge.
|
||||
//func newDNS01Challenge(db nosql.DB, ops ChallengeOptions) (challenge, error) {
|
||||
// bc, err := newBaseChallenge(ops.AccountID, ops.AuthzID)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// bc.Type = "dns-01"
|
||||
// bc.Value = ops.Identifier.Value
|
||||
//
|
||||
// dc := &dns01Challenge{bc}
|
||||
// if err := dc.save(db, nil); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return dc, nil
|
||||
//}
|
||||
//
|
||||
//// KeyAuthorization creates the ACME key authorization value from a token
|
||||
//// and a jwk.
|
||||
//func KeyAuthorization(token string, jwk *jose.JSONWebKey) (string, error) {
|
||||
// thumbprint, err := jwk.Thumbprint(crypto.SHA256)
|
||||
// if err != nil {
|
||||
// return "", ServerInternalErr(errors.Wrap(err, "error generating JWK thumbprint"))
|
||||
// }
|
||||
// encPrint := base64.RawURLEncoding.EncodeToString(thumbprint)
|
||||
// return fmt.Sprintf("%s.%s", token, encPrint), nil
|
||||
//}
|
||||
//
|
||||
//// validate attempts to validate the challenge. If the challenge has been
|
||||
//// satisfactorily validated, the 'status' and 'validated' attributes are
|
||||
//// updated.
|
||||
//func (dc *dns01Challenge) validate(db nosql.DB, jwk *jose.JSONWebKey, vo validateOptions) (challenge, error) {
|
||||
// // If already valid or invalid then return without performing validation.
|
||||
// if dc.getStatus() == StatusValid || dc.getStatus() == StatusInvalid {
|
||||
// return dc, nil
|
||||
// }
|
||||
//
|
||||
// // Normalize domain for wildcard DNS names
|
||||
// // This is done to avoid making TXT lookups for domains like
|
||||
// // _acme-challenge.*.example.com
|
||||
// // Instead perform txt lookup for _acme-challenge.example.com
|
||||
// domain := strings.TrimPrefix(dc.Value, "*.")
|
||||
//
|
||||
// txtRecords, err := vo.lookupTxt("_acme-challenge." + domain)
|
||||
// if err != nil {
|
||||
// if err = dc.storeError(db,
|
||||
// DNSErr(errors.Wrapf(err, "error looking up TXT "+
|
||||
// "records for domain %s", domain))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return dc, nil
|
||||
// }
|
||||
//
|
||||
// expectedKeyAuth, err := KeyAuthorization(dc.Token, jwk)
|
||||
// if err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// h := sha256.Sum256([]byte(expectedKeyAuth))
|
||||
// expected := base64.RawURLEncoding.EncodeToString(h[:])
|
||||
// var found bool
|
||||
// for _, r := range txtRecords {
|
||||
// if r == expected {
|
||||
// found = true
|
||||
// break
|
||||
// }
|
||||
// }
|
||||
// if !found {
|
||||
// if err = dc.storeError(db,
|
||||
// RejectedIdentifierErr(errors.Errorf("keyAuthorization "+
|
||||
// "does not match; expected %s, but got %s", expectedKeyAuth, txtRecords))); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return dc, nil
|
||||
// }
|
||||
//
|
||||
// // Update and store the challenge.
|
||||
// upd := &dns01Challenge{dc.baseChallenge.clone()}
|
||||
// upd.Status = StatusValid
|
||||
// upd.Error = nil
|
||||
// upd.Validated = time.Now().UTC()
|
||||
//
|
||||
// if err := upd.save(db, dc); err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// return upd, nil
|
||||
//}
|
||||
//
|
||||
//// unmarshalChallenge unmarshals a challenge type into the correct sub-type.
|
||||
//func unmarshalChallenge(data []byte) (challenge, error) {
|
||||
// var getType struct {
|
||||
// Type string `json:"type"`
|
||||
// }
|
||||
// if err := json.Unmarshal(data, &getType); err != nil {
|
||||
// return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling challenge type"))
|
||||
// }
|
||||
//
|
||||
// switch getType.Type {
|
||||
// case "dns-01":
|
||||
// var bc baseChallenge
|
||||
// if err := json.Unmarshal(data, &bc); err != nil {
|
||||
// return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
|
||||
// "challenge type into dns01Challenge"))
|
||||
// }
|
||||
// return &dns01Challenge{&bc}, nil
|
||||
// case "http-01":
|
||||
// var bc baseChallenge
|
||||
// if err := json.Unmarshal(data, &bc); err != nil {
|
||||
// return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
|
||||
// "challenge type into http01Challenge"))
|
||||
// }
|
||||
// return &http01Challenge{&bc}, nil
|
||||
// case "tls-alpn-01":
|
||||
// var bc baseChallenge
|
||||
// if err := json.Unmarshal(data, &bc); err != nil {
|
||||
// return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling "+
|
||||
// "challenge type into tlsALPN01Challenge"))
|
||||
// }
|
||||
// return &tlsALPN01Challenge{&bc}, nil
|
||||
// default:
|
||||
// return nil, ServerInternalErr(errors.Errorf("unexpected challenge type '%s'", getType.Type))
|
||||
// }
|
||||
//}
|
||||
//
|
|
@ -0,0 +1,469 @@
|
|||
package nosql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/smallstep/certificates/authority/provisioner"
|
||||
"github.com/smallstep/nosql"
|
||||
"go.step.sm/crypto/x509util"
|
||||
)
|
||||
|
||||
var defaultOrderExpiry = time.Hour * 24
|
||||
|
||||
// Mutex for locking ordersByAccount index operations.
|
||||
var ordersByAccountMux sync.Mutex
|
||||
|
||||
// OrderOptions options with which to create a new Order.
|
||||
type OrderOptions struct {
|
||||
AccountID string `json:"accID"`
|
||||
Identifiers []Identifier `json:"identifiers"`
|
||||
NotBefore time.Time `json:"notBefore"`
|
||||
NotAfter time.Time `json:"notAfter"`
|
||||
backdate time.Duration
|
||||
defaultDuration time.Duration
|
||||
}
|
||||
|
||||
type dbOrder struct {
|
||||
ID string `json:"id"`
|
||||
AccountID string `json:"accountID"`
|
||||
Created time.Time `json:"created"`
|
||||
Expires time.Time `json:"expires,omitempty"`
|
||||
Status string `json:"status"`
|
||||
Identifiers []Identifier `json:"identifiers"`
|
||||
NotBefore time.Time `json:"notBefore,omitempty"`
|
||||
NotAfter time.Time `json:"notAfter,omitempty"`
|
||||
Error *Error `json:"error,omitempty"`
|
||||
Authorizations []string `json:"authorizations"`
|
||||
Certificate string `json:"certificate,omitempty"`
|
||||
}
|
||||
|
||||
// getDBOrder retrieves and unmarshals an ACME Order type from the database.
|
||||
func (db *DB) getDBOrder(id string) (*dbOrder, error) {
|
||||
b, err := db.db.Get(orderTable, []byte(id))
|
||||
if nosql.IsErrNotFound(err) {
|
||||
return nil, MalformedErr(errors.Wrapf(err, "order %s not found", id))
|
||||
} else if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error loading order %s", id))
|
||||
}
|
||||
o := new(dbOrder)
|
||||
if err := json.Unmarshal(b, &o); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error unmarshaling order"))
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
// GetOrder retrieves an ACME Order from the database.
|
||||
func (db *DB) GetOrder(id string) (*types.Order, error) {
|
||||
dbo, err := db.getDBOrder(id)
|
||||
|
||||
azs := make([]string, len(dbo.Authorizations))
|
||||
for i, aid := range dbo.Authorizations {
|
||||
azs[i] = dir.getLink(ctx, AuthzLink, true, aid)
|
||||
}
|
||||
o := &Order{
|
||||
Status: dbo.Status,
|
||||
Expires: dbo.Expires.Format(time.RFC3339),
|
||||
Identifiers: dbo.Identifiers,
|
||||
NotBefore: dbo.NotBefore.Format(time.RFC3339),
|
||||
NotAfter: dbo.NotAfter.Format(time.RFC3339),
|
||||
Authorizations: azs,
|
||||
Finalize: dir.getLink(ctx, FinalizeLink, true, o.ID),
|
||||
ID: dbo.ID,
|
||||
}
|
||||
|
||||
if dbo.Certificate != "" {
|
||||
o.Certificate = dir.getLink(ctx, CertificateLink, true, o.Certificate)
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
// newOrder returns a new Order type.
|
||||
func newOrder(db nosql.DB, ops OrderOptions) (*order, error) {
|
||||
id, err := randID()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
authzs := make([]string, len(ops.Identifiers))
|
||||
for i, identifier := range ops.Identifiers {
|
||||
az, err := newAuthz(db, ops.AccountID, identifier)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
authzs[i] = az.getID()
|
||||
}
|
||||
|
||||
now := clock.Now()
|
||||
var backdate time.Duration
|
||||
nbf := ops.NotBefore
|
||||
if nbf.IsZero() {
|
||||
nbf = now
|
||||
backdate = -1 * ops.backdate
|
||||
}
|
||||
naf := ops.NotAfter
|
||||
if naf.IsZero() {
|
||||
naf = nbf.Add(ops.defaultDuration)
|
||||
}
|
||||
|
||||
o := &order{
|
||||
ID: id,
|
||||
AccountID: ops.AccountID,
|
||||
Created: now,
|
||||
Status: StatusPending,
|
||||
Expires: now.Add(defaultOrderExpiry),
|
||||
Identifiers: ops.Identifiers,
|
||||
NotBefore: nbf.Add(backdate),
|
||||
NotAfter: naf,
|
||||
Authorizations: authzs,
|
||||
}
|
||||
if err := o.save(db, nil); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var oidHelper = orderIDsByAccount{}
|
||||
_, err = oidHelper.addOrderID(db, ops.AccountID, o.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return o, nil
|
||||
}
|
||||
|
||||
type orderIDsByAccount struct{}
|
||||
|
||||
// addOrderID adds an order ID to a users index of in progress order IDs.
|
||||
// This method will also cull any orders that are no longer in the `pending`
|
||||
// state from the index before returning it.
|
||||
func (oiba orderIDsByAccount) addOrderID(db nosql.DB, accID string, oid string) ([]string, error) {
|
||||
ordersByAccountMux.Lock()
|
||||
defer ordersByAccountMux.Unlock()
|
||||
|
||||
// Update the "order IDs by account ID" index
|
||||
oids, err := oiba.unsafeGetOrderIDsByAccount(db, accID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
newOids := append(oids, oid)
|
||||
if err = orderIDs(newOids).save(db, oids, accID); err != nil {
|
||||
// Delete the entire order if storing the index fails.
|
||||
db.Del(orderTable, []byte(oid))
|
||||
return nil, err
|
||||
}
|
||||
return newOids, nil
|
||||
}
|
||||
|
||||
// unsafeGetOrderIDsByAccount retrieves a list of Order IDs that were created by the
|
||||
// account.
|
||||
func (oiba orderIDsByAccount) unsafeGetOrderIDsByAccount(db nosql.DB, accID string) ([]string, error) {
|
||||
b, err := db.Get(ordersByAccountIDTable, []byte(accID))
|
||||
if err != nil {
|
||||
if nosql.IsErrNotFound(err) {
|
||||
return []string{}, nil
|
||||
}
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error loading orderIDs for account %s", accID))
|
||||
}
|
||||
var oids []string
|
||||
if err := json.Unmarshal(b, &oids); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error unmarshaling orderIDs for account %s", accID))
|
||||
}
|
||||
|
||||
// Remove any order that is not in PENDING state and update the stored list
|
||||
// before returning.
|
||||
//
|
||||
// According to RFC 8555:
|
||||
// The server SHOULD include pending orders and SHOULD NOT include orders
|
||||
// that are invalid in the array of URLs.
|
||||
pendOids := []string{}
|
||||
for _, oid := range oids {
|
||||
o, err := getOrder(db, oid)
|
||||
if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error loading order %s for account %s", oid, accID))
|
||||
}
|
||||
if o, err = o.updateStatus(db); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error updating order %s for account %s", oid, accID))
|
||||
}
|
||||
if o.Status == StatusPending {
|
||||
pendOids = append(pendOids, oid)
|
||||
}
|
||||
}
|
||||
// If the number of pending orders is less than the number of orders in the
|
||||
// list, then update the pending order list.
|
||||
if len(pendOids) != len(oids) {
|
||||
if err = orderIDs(pendOids).save(db, oids, accID); err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error storing orderIDs as part of getOrderIDsByAccount logic: "+
|
||||
"len(orderIDs) = %d", len(pendOids)))
|
||||
}
|
||||
}
|
||||
|
||||
return pendOids, nil
|
||||
}
|
||||
|
||||
type orderIDs []string
|
||||
|
||||
// save is used to update the list of orderIDs keyed by ACME account ID
|
||||
// stored in the database.
|
||||
//
|
||||
// This method always converts empty lists to 'nil' when storing to the DB. We
|
||||
// do this to avoid any confusion between an empty list and a nil value in the
|
||||
// db.
|
||||
func (oids orderIDs) save(db nosql.DB, old orderIDs, accID string) error {
|
||||
var (
|
||||
err error
|
||||
oldb []byte
|
||||
newb []byte
|
||||
)
|
||||
if len(old) == 0 {
|
||||
oldb = nil
|
||||
} else {
|
||||
oldb, err = json.Marshal(old)
|
||||
if err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err, "error marshaling old order IDs slice"))
|
||||
}
|
||||
}
|
||||
if len(oids) == 0 {
|
||||
newb = nil
|
||||
} else {
|
||||
newb, err = json.Marshal(oids)
|
||||
if err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err, "error marshaling new order IDs slice"))
|
||||
}
|
||||
}
|
||||
_, swapped, err := db.CmpAndSwap(ordersByAccountIDTable, []byte(accID), oldb, newb)
|
||||
switch {
|
||||
case err != nil:
|
||||
return ServerInternalErr(errors.Wrapf(err, "error storing order IDs for account %s", accID))
|
||||
case !swapped:
|
||||
return ServerInternalErr(errors.Errorf("error storing order IDs "+
|
||||
"for account %s; order IDs changed since last read", accID))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (o *order) save(db nosql.DB, old *order) error {
|
||||
var (
|
||||
err error
|
||||
oldB []byte
|
||||
)
|
||||
if old == nil {
|
||||
oldB = nil
|
||||
} else {
|
||||
if oldB, err = json.Marshal(old); err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err, "error marshaling old acme order"))
|
||||
}
|
||||
}
|
||||
|
||||
newB, err := json.Marshal(o)
|
||||
if err != nil {
|
||||
return ServerInternalErr(errors.Wrap(err, "error marshaling new acme order"))
|
||||
}
|
||||
|
||||
_, swapped, err := db.CmpAndSwap(orderTable, []byte(o.ID), oldB, newB)
|
||||
switch {
|
||||
case err != nil:
|
||||
return ServerInternalErr(errors.Wrap(err, "error storing order"))
|
||||
case !swapped:
|
||||
return ServerInternalErr(errors.New("error storing order; " +
|
||||
"value has changed since last read"))
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
// updateStatus updates order status if necessary.
|
||||
func (o *order) updateStatus(db nosql.DB) (*order, error) {
|
||||
_newOrder := *o
|
||||
newOrder := &_newOrder
|
||||
|
||||
now := time.Now().UTC()
|
||||
switch o.Status {
|
||||
case StatusInvalid:
|
||||
return o, nil
|
||||
case StatusValid:
|
||||
return o, nil
|
||||
case StatusReady:
|
||||
// check expiry
|
||||
if now.After(o.Expires) {
|
||||
newOrder.Status = StatusInvalid
|
||||
newOrder.Error = MalformedErr(errors.New("order has expired"))
|
||||
break
|
||||
}
|
||||
return o, nil
|
||||
case StatusPending:
|
||||
// check expiry
|
||||
if now.After(o.Expires) {
|
||||
newOrder.Status = StatusInvalid
|
||||
newOrder.Error = MalformedErr(errors.New("order has expired"))
|
||||
break
|
||||
}
|
||||
|
||||
var count = map[string]int{
|
||||
StatusValid: 0,
|
||||
StatusInvalid: 0,
|
||||
StatusPending: 0,
|
||||
}
|
||||
for _, azID := range o.Authorizations {
|
||||
az, err := getAuthz(db, azID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if az, err = az.updateStatus(db); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
st := az.getStatus()
|
||||
count[st]++
|
||||
}
|
||||
switch {
|
||||
case count[StatusInvalid] > 0:
|
||||
newOrder.Status = StatusInvalid
|
||||
|
||||
// No change in the order status, so just return the order as is -
|
||||
// without writing any changes.
|
||||
case count[StatusPending] > 0:
|
||||
return newOrder, nil
|
||||
|
||||
case count[StatusValid] == len(o.Authorizations):
|
||||
newOrder.Status = StatusReady
|
||||
|
||||
default:
|
||||
return nil, ServerInternalErr(errors.New("unexpected authz status"))
|
||||
}
|
||||
default:
|
||||
return nil, ServerInternalErr(errors.Errorf("unrecognized order status: %s", o.Status))
|
||||
}
|
||||
|
||||
if err := newOrder.save(db, o); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newOrder, nil
|
||||
}
|
||||
|
||||
// finalize signs a certificate if the necessary conditions for Order completion
|
||||
// have been met.
|
||||
func (o *order) finalize(db nosql.DB, csr *x509.CertificateRequest, auth SignAuthority, p Provisioner) (*order, error) {
|
||||
var err error
|
||||
if o, err = o.updateStatus(db); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch o.Status {
|
||||
case StatusInvalid:
|
||||
return nil, OrderNotReadyErr(errors.Errorf("order %s has been abandoned", o.ID))
|
||||
case StatusValid:
|
||||
return o, nil
|
||||
case StatusPending:
|
||||
return nil, OrderNotReadyErr(errors.Errorf("order %s is not ready", o.ID))
|
||||
case StatusReady:
|
||||
break
|
||||
default:
|
||||
return nil, ServerInternalErr(errors.Errorf("unexpected status %s for order %s", o.Status, o.ID))
|
||||
}
|
||||
|
||||
// RFC8555: The CSR MUST indicate the exact same set of requested
|
||||
// identifiers as the initial newOrder request. Identifiers of type "dns"
|
||||
// MUST appear either in the commonName portion of the requested subject
|
||||
// name or in an extensionRequest attribute [RFC2985] requesting a
|
||||
// subjectAltName extension, or both.
|
||||
if csr.Subject.CommonName != "" {
|
||||
csr.DNSNames = append(csr.DNSNames, csr.Subject.CommonName)
|
||||
}
|
||||
csr.DNSNames = uniqueLowerNames(csr.DNSNames)
|
||||
orderNames := make([]string, len(o.Identifiers))
|
||||
for i, n := range o.Identifiers {
|
||||
orderNames[i] = n.Value
|
||||
}
|
||||
orderNames = uniqueLowerNames(orderNames)
|
||||
|
||||
// Validate identifier names against CSR alternative names.
|
||||
//
|
||||
// Note that with certificate templates we are not going to check for the
|
||||
// absence of other SANs as they will only be set if the templates allows
|
||||
// them.
|
||||
if len(csr.DNSNames) != len(orderNames) {
|
||||
return nil, BadCSRErr(errors.Errorf("CSR names do not match identifiers exactly: CSR names = %v, Order names = %v", csr.DNSNames, orderNames))
|
||||
}
|
||||
|
||||
sans := make([]x509util.SubjectAlternativeName, len(csr.DNSNames))
|
||||
for i := range csr.DNSNames {
|
||||
if csr.DNSNames[i] != orderNames[i] {
|
||||
return nil, BadCSRErr(errors.Errorf("CSR names do not match identifiers exactly: CSR names = %v, Order names = %v", csr.DNSNames, orderNames))
|
||||
}
|
||||
sans[i] = x509util.SubjectAlternativeName{
|
||||
Type: x509util.DNSType,
|
||||
Value: csr.DNSNames[i],
|
||||
}
|
||||
}
|
||||
|
||||
// Get authorizations from the ACME provisioner.
|
||||
ctx := provisioner.NewContextWithMethod(context.Background(), provisioner.SignMethod)
|
||||
signOps, err := p.AuthorizeSign(ctx, "")
|
||||
if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error retrieving authorization options from ACME provisioner"))
|
||||
}
|
||||
|
||||
// Template data
|
||||
data := x509util.NewTemplateData()
|
||||
data.SetCommonName(csr.Subject.CommonName)
|
||||
data.Set(x509util.SANsKey, sans)
|
||||
|
||||
templateOptions, err := provisioner.TemplateOptions(p.GetOptions(), data)
|
||||
if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error creating template options from ACME provisioner"))
|
||||
}
|
||||
signOps = append(signOps, templateOptions)
|
||||
|
||||
// Create and store a new certificate.
|
||||
certChain, err := auth.Sign(csr, provisioner.SignOptions{
|
||||
NotBefore: provisioner.NewTimeDuration(o.NotBefore),
|
||||
NotAfter: provisioner.NewTimeDuration(o.NotAfter),
|
||||
}, signOps...)
|
||||
if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrapf(err, "error generating certificate for order %s", o.ID))
|
||||
}
|
||||
|
||||
cert, err := newCert(db, CertOptions{
|
||||
AccountID: o.AccountID,
|
||||
OrderID: o.ID,
|
||||
Leaf: certChain[0],
|
||||
Intermediates: certChain[1:],
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_newOrder := *o
|
||||
newOrder := &_newOrder
|
||||
newOrder.Certificate = cert.ID
|
||||
newOrder.Status = StatusValid
|
||||
if err := newOrder.save(db, o); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return newOrder, nil
|
||||
}
|
||||
|
||||
// toACME converts the internal Order type into the public acmeOrder type for
|
||||
// presentation in the ACME protocol.
|
||||
func (o *order) toACME(ctx context.Context, db nosql.DB, dir *directory) (*Order, error) {
|
||||
}
|
||||
|
||||
// uniqueLowerNames returns the set of all unique names in the input after all
|
||||
// of them are lowercased. The returned names will be in their lowercased form
|
||||
// and sorted alphabetically.
|
||||
func uniqueLowerNames(names []string) (unique []string) {
|
||||
nameMap := make(map[string]int, len(names))
|
||||
for _, name := range names {
|
||||
nameMap[strings.ToLower(name)] = 1
|
||||
}
|
||||
unique = make([]string, 0, len(nameMap))
|
||||
for name := range nameMap {
|
||||
unique = append(unique, name)
|
||||
}
|
||||
sort.Strings(unique)
|
||||
return
|
||||
}
|
|
@ -6,15 +6,15 @@ import (
|
|||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Authz is a subset of the Authz type containing only those attributes
|
||||
// required for responses in the ACME protocol.
|
||||
type Authz struct {
|
||||
// Authorization representst an ACME Authorization.
|
||||
type Authorization struct {
|
||||
Identifier Identifier `json:"identifier"`
|
||||
Status string `json:"status"`
|
||||
Expires string `json:"expires"`
|
||||
Challenges []*Challenge `json:"challenges"`
|
||||
Wildcard bool `json:"wildcard"`
|
||||
ID string `json:"-"`
|
||||
AccountID string `json:"-"`
|
||||
}
|
||||
|
||||
// ToLog enables response logging.
|
||||
|
@ -25,8 +25,3 @@ func (a *Authz) ToLog() (interface{}, error) {
|
|||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// GetID returns the Authz ID.
|
||||
func (a *Authz) GetID() string {
|
||||
return a.ID
|
||||
}
|
||||
|
|
30
acme/types/challenge.go
Normal file
30
acme/types/challenge.go
Normal file
|
@ -0,0 +1,30 @@
|
|||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Challenge represents an ACME response Challenge type.
|
||||
type Challenge struct {
|
||||
Type string `json:"type"`
|
||||
Status string `json:"status"`
|
||||
Token string `json:"token"`
|
||||
Validated string `json:"validated,omitempty"`
|
||||
URL string `json:"url"`
|
||||
Error *AError `json:"error,omitempty"`
|
||||
ID string `json:"-"`
|
||||
AuthzID string `json:"-"`
|
||||
AccountID string `json:"-"`
|
||||
Value string `json:"-"`
|
||||
}
|
||||
|
||||
// ToLog enables response logging.
|
||||
func (c *Challenge) ToLog() (interface{}, error) {
|
||||
b, err := json.Marshal(c)
|
||||
if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error marshaling challenge for logging"))
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
30
acme/types/order.go
Normal file
30
acme/types/order.go
Normal file
|
@ -0,0 +1,30 @@
|
|||
package types
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
// Order contains order metadata for the ACME protocol order type.
|
||||
type Order struct {
|
||||
Status string `json:"status"`
|
||||
Expires string `json:"expires,omitempty"`
|
||||
Identifiers []Identifier `json:"identifiers"`
|
||||
NotBefore string `json:"notBefore,omitempty"`
|
||||
NotAfter string `json:"notAfter,omitempty"`
|
||||
Error interface{} `json:"error,omitempty"`
|
||||
Authorizations []string `json:"authorizations"`
|
||||
Finalize string `json:"finalize"`
|
||||
Certificate string `json:"certificate,omitempty"`
|
||||
ID string `json:"-"`
|
||||
}
|
||||
|
||||
// ToLog enables response logging.
|
||||
func (o *Order) ToLog() (interface{}, error) {
|
||||
b, err := json.Marshal(o)
|
||||
if err != nil {
|
||||
return nil, ServerInternalErr(errors.Wrap(err, "error marshaling order for logging"))
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
20
acme/types/status.go
Normal file
20
acme/types/status.go
Normal file
|
@ -0,0 +1,20 @@
|
|||
package types
|
||||
|
||||
// Status represents an ACME status.
|
||||
type Status string
|
||||
|
||||
var (
|
||||
// StatusValid -- valid
|
||||
StatusValid = Status("valid")
|
||||
// StatusInvalid -- invalid
|
||||
StatusInvalid = Status("invalid")
|
||||
// StatusPending -- pending; e.g. an Order that is not ready to be finalized.
|
||||
StatusPending = Status("pending")
|
||||
// StatusDeactivated -- deactivated; e.g. for an Account that is not longer valid.
|
||||
StatusDeactivated = Status("deactivated")
|
||||
// StatusReady -- ready; e.g. for an Order that is ready to be finalized.
|
||||
StatusReady = Status("ready")
|
||||
//statusExpired = "expired"
|
||||
//statusActive = "active"
|
||||
//statusProcessing = "processing"
|
||||
)
|
Loading…
Reference in a new issue