Skip to content

Commit

Permalink
Merge pull request #4 from zllovesuki/xor
Browse files Browse the repository at this point in the history
  • Loading branch information
zllovesuki authored Feb 9, 2022
2 parents eda4f58 + 2850890 commit cfc8ec7
Show file tree
Hide file tree
Showing 29 changed files with 306 additions and 357 deletions.
68 changes: 35 additions & 33 deletions acme/acme.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,15 @@ import (
"crypto/x509/pkix"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"os"
"path"
"strings"
"sync"
"time"

"github.com/eggsampler/acme/v3"
"github.com/pkg/errors"
)

type CertManager struct {
Expand Down Expand Up @@ -64,7 +65,7 @@ func New(conf Config) (*CertManager, error) {
}
client, err := acme.NewClient(conf.Directory, acme.WithHTTPTimeout(time.Second*10))
if err != nil {
return nil, errors.Wrap(err, "initializing acme client")
return nil, fmt.Errorf("initializing acme client: %w", err)
}
c := &CertManager{
client: client,
Expand All @@ -84,17 +85,17 @@ func (c *CertManager) CreateAccount() error {
var err error
c.accKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return errors.Wrap(err, "generating new account private key")
return fmt.Errorf("generating new account private key: %w", err)
}
c.account, err = c.client.NewAccountOptions(c.accKey, acme.NewAcctOptAgreeTOS(), acme.NewAcctOptWithContacts(c.config.Contact))
if err != nil {
return errors.Wrap(err, "creating account with CA")
return fmt.Errorf("creating account with CA: %w", err)
}
c.hasAcc = true

pem, err := keyToPEM(c.accKey)
if err != nil {
return errors.Wrap(err, "converting pkey to pem")
return fmt.Errorf("converting pkey to pem: %w", err)
}
af := AccountFile{
PrivateKey: string(pem),
Expand All @@ -106,25 +107,25 @@ func (c *CertManager) CreateAccount() error {
func (c *CertManager) persistAccount(af AccountFile) error {
w, err := os.Create(path.Join(c.config.DataDir, "accounts.json"))
if err != nil {
return errors.Wrap(err, "opening accounts.json for writing")
return fmt.Errorf("opening accounts.json for writing: %w", err)
}
defer w.Close()
err = json.NewEncoder(w).Encode(&af)
if err != nil {
return errors.Wrap(err, "writing to accounts.json")
return fmt.Errorf("writing to accounts.json: %w", err)
}
return nil
}

func (c *CertManager) persisCerts(bundle Bundle) error {
w, err := os.Create(path.Join(c.config.DataDir, "bundle.json"))
if err != nil {
return errors.Wrap(err, "opening bundle.json for writing")
return fmt.Errorf("opening bundle.json for writing: %w", err)
}
defer w.Close()
err = json.NewEncoder(w).Encode(&bundle)
if err != nil {
return errors.Wrap(err, "writing to bundle.json")
return fmt.Errorf("writing to bundle.json: %w", err)
}
return nil
}
Expand All @@ -138,7 +139,7 @@ func (c *CertManager) ExportAccount() (*AccountFile, error) {
}
pem, err := keyToPEM(c.accKey)
if err != nil {
return nil, errors.Wrap(err, "converting pkey to pem")
return nil, fmt.Errorf("converting pkey to pem: %w", err)
}
af := AccountFile{
PrivateKey: string(pem),
Expand All @@ -153,14 +154,14 @@ func (c *CertManager) LoadAccountFromFile() error {
if errors.Is(err, os.ErrNotExist) {
return ErrNoAccount
}
return errors.Wrap(err, "loading accounts.json")
return fmt.Errorf("loading accounts.json: %w", err)
}
defer f.Close()

var af AccountFile
err = json.NewDecoder(f).Decode(&af)
if err != nil {
return errors.Wrap(err, "decoding accounts.json")
return fmt.Errorf("decoding accounts.json: %w", err)
}

return c.ImportAccount(af, false)
Expand All @@ -172,14 +173,14 @@ func (c *CertManager) LoadBundleFromFile() error {
if errors.Is(err, os.ErrNotExist) {
return ErrNoCert
}
return errors.Wrap(err, "loading bundle.json")
return fmt.Errorf("loading bundle.json: %w", err)
}
defer f.Close()

var bundle Bundle
err = json.NewDecoder(f).Decode(&bundle)
if err != nil {
return errors.Wrap(err, "decoding bundle.json")
return fmt.Errorf("decoding bundle.json: %w", err)
}

return c.ImportBundle(bundle, false)
Expand All @@ -195,15 +196,15 @@ func (c *CertManager) ImportAccount(af AccountFile, persist bool) error {

pKey, err := pemToKey([]byte(af.PrivateKey))
if err != nil {
return errors.Wrap(err, "converting pem to pkey")
return fmt.Errorf("converting pem to pkey: %w", err)
}
c.account, err = c.client.UpdateAccount(acme.Account{
PrivateKey: pKey,
URL: af.URL,
}, c.config.Contact)

if err != nil {
return errors.Wrap(err, "reloading accounts")
return fmt.Errorf("reloading accounts: %w", err)
}

c.hasAcc = true
Expand All @@ -226,7 +227,7 @@ func (c *CertManager) ImportPrivateKey(keyPem string) error {
var err error
c.certPKey, err = pemToKey([]byte(keyPem))
if err != nil {
return errors.Wrap(err, "decoding private key from pem")
return fmt.Errorf("decoding private key from pem: %w", err)
}
return nil
}
Expand All @@ -241,22 +242,22 @@ func (c *CertManager) ExportPrivateKey() ([]byte, error) {

pKey, err := keyToPEM(c.certPKey)
if err != nil {
return nil, errors.Wrap(err, "encoding private key to pem")
return nil, fmt.Errorf("encoding private key to pem: %w", err)
}
return pKey, nil
}

func (c *CertManager) ImportBundle(bundle Bundle, persist bool) error {
pKey, err := pemToKey([]byte(bundle.PrivateKey))
if err != nil {
return errors.Wrap(err, "decoding private key")
return fmt.Errorf("decoding private key: %w", err)
}
cert, err := tls.X509KeyPair(
[]byte(strings.Join(bundle.Chain, "\n")),
[]byte(bundle.PrivateKey),
)
if err != nil {
return errors.Wrap(err, "generating x509 key pair")
return fmt.Errorf("generating x509 key pair: %w", err)
}
c.certPKeyMu.Lock()
c.certMu.Lock()
Expand Down Expand Up @@ -300,6 +301,7 @@ func (c *CertManager) RequestCertificate() error {
common := c.config.RootZone
apex := strings.TrimSuffix(c.config.Domain, c.config.RootZone)
apex = strings.TrimSuffix(apex, ".")
// TODO: the following routine is not robust
switch {
case apex == "":
case apex[0] == 0x2a: // the "*" character
Expand All @@ -323,7 +325,7 @@ func (c *CertManager) RequestCertificate() error {
c.certPKey, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
c.certPKeyMu.Unlock()
return errors.Wrap(err, "generating certificate private key")
return fmt.Errorf("generating certificate private key: %w", err)
}
c.hasCertPKey = true
}
Expand All @@ -339,29 +341,29 @@ func (c *CertManager) RequestCertificate() error {
c.certPKeyMu.Unlock()

if err != nil {
return errors.Wrap(err, "generating csr")
return fmt.Errorf("generating csr: %w", err)
}
csr, err := x509.ParseCertificateRequest(csrDer)
if err != nil {
return errors.Wrap(err, "parsing csr")
return fmt.Errorf("parsing csr: %w", err)
}

var pKey []byte
pKey, err = c.ExportPrivateKey()
if err != nil {
return errors.Wrap(err, "encoding private key to pem")
return fmt.Errorf("encoding private key to pem: %w", err)
}

// now we can create a order
o, err := c.client.NewOrderDomains(c.account, names...)
if err != nil {
return errors.Wrap(err, "creating order")
return fmt.Errorf("creating order: %w", err)
}

for _, authURL := range o.Authorizations {
auth, err := c.client.FetchAuthorization(c.account, authURL)
if err != nil {
return errors.Wrap(err, "fetching authorization")
return fmt.Errorf("fetching authoriztion: %w", err)
}
chal, ok := auth.ChallengeMap[acme.ChallengeTypeDNS01]
if !ok {
Expand All @@ -376,15 +378,15 @@ func (c *CertManager) RequestCertificate() error {

ok, err = c.config.DNSProvider.Update(ctx, host, "TXT", txt)
if err != nil {
return errors.Wrap(err, "updating dns record")
return fmt.Errorf("updating dns record: %w", err)
}
if !ok {
return errors.New("dns update failed")
}

chal, err = c.client.UpdateChallenge(c.account, chal)
if err != nil {
return errors.Wrap(err, "updating challenge")
return fmt.Errorf("updating challenge: %w", err)
}
return nil
}()
Expand All @@ -398,12 +400,12 @@ func (c *CertManager) RequestCertificate() error {

o, err = c.client.FinalizeOrder(c.account, o, csr)
if err != nil {
return errors.Wrap(err, "finalizing order")
return fmt.Errorf("finalizing order: %w", err)
}

certs, err := c.client.FetchCertificates(c.account, o.Certificate)
if err != nil {
return errors.Wrap(err, "fetching certificates")
return fmt.Errorf("fetching certificates: %w", err)
}

var pemData []string
Expand All @@ -420,7 +422,7 @@ func (c *CertManager) RequestCertificate() error {
}

if err := c.ImportBundle(bundle, true); err != nil {
return errors.Wrap(err, "re-importing exported certificate")
return fmt.Errorf("re-importing exported certificate: %w", err)
}

return nil
Expand All @@ -438,7 +440,7 @@ func (c *CertManager) GetCertificatesFunc(chi *tls.ClientHelloInfo) (*tls.Certif
func keyToPEM(pKey *ecdsa.PrivateKey) ([]byte, error) {
enc, err := x509.MarshalECPrivateKey(pKey)
if err != nil {
return nil, errors.Wrap(err, "marshaling private key to pem")
return nil, fmt.Errorf("marshalling private key to pem: %w", err)
}
return pem.EncodeToMemory(&pem.Block{
Type: "EC PRIVATE KEY",
Expand All @@ -450,7 +452,7 @@ func pemToKey(b []byte) (*ecdsa.PrivateKey, error) {
blk, _ := pem.Decode(b)
pKey, err := x509.ParseECPrivateKey(blk.Bytes)
if err != nil {
return nil, errors.Wrap(err, "parsing private key from pem")
return nil, fmt.Errorf("parsing private key from pem: %w", err)
}
return pKey, nil
}
4 changes: 3 additions & 1 deletion client/forward.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ import (

type ForwardOpts struct {
Logger *zap.Logger
Sigs chan os.Signal
URL string
Addr string
Debug bool
Sigs chan os.Signal
_ [7]byte
_ [8]byte
}

func Forward(ctx context.Context, opts ForwardOpts) {
Expand Down
8 changes: 4 additions & 4 deletions cmd/server/authz.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ package main

import (
"crypto/tls"
"errors"
"fmt"
"strings"

"github.com/pkg/errors"
)

func checkClientSNI(domain string) func(tls.ConnectionState) error {
return func(cs tls.ConnectionState) error {
if !strings.HasSuffix(cs.ServerName, domain) {
return errors.Errorf("unauthorized domain name: %s", cs.ServerName)
return fmt.Errorf("unauthorized domain name: %s", cs.ServerName)
}
return nil
}
Expand All @@ -26,7 +26,7 @@ func checkPeerSAN(required string) func(tls.ConnectionState) error {
found = found || name == required
}
if !found {
return errors.Errorf("%s must be present in SANs", required)
return fmt.Errorf("%s must be present in SANs", required)
}
return nil
}
Expand Down
5 changes: 3 additions & 2 deletions cmd/server/config.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package main

import (
"fmt"

"github.com/zllovesuki/t/acme"
"github.com/zllovesuki/t/multiplexer/protocol"
"github.com/zllovesuki/t/provider"
"github.com/zllovesuki/t/server"

"github.com/gookit/config/v2"
"github.com/gookit/config/v2/yaml"
"github.com/pkg/errors"
)

type WebConfig struct {
Expand Down Expand Up @@ -39,7 +40,7 @@ func getConfig(path string) (*ConfigBundle, error) {

err := cfg.LoadFiles(path)
if err != nil {
return nil, errors.Wrap(err, "loading config file")
return nil, fmt.Errorf("loading config file: %w", err)
}

var bundle ConfigBundle
Expand Down
2 changes: 1 addition & 1 deletion example.config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ acme:
zone: example.com
tsigKey: sign.
tsigSecret: yoursecrethere==
tsigAlgo: hmac-sha256
tsigAlgo: hmac-sha256.
nameserver: dns.example.com:53

network:
Expand Down
5 changes: 2 additions & 3 deletions gateway/gateway.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ import (
"github.com/zllovesuki/t/server"
"github.com/zllovesuki/t/shared"

"github.com/pkg/errors"
"go.uber.org/zap"
)

Expand All @@ -37,11 +36,11 @@ type Gateway struct {
func New(conf GatewayConfig) (*Gateway, error) {
md, err := template.New("content").Parse(tmpl)
if err != nil {
return nil, errors.Wrap(err, "reading markdown for apex template")
return nil, fmt.Errorf("reading markdown for apex template: %w", err)
}
idx, err := template.New("index").Parse(index)
if err != nil {
return nil, errors.Wrap(err, "reading index for apex template")
return nil, fmt.Errorf("reading index for apex template: %w", err)
}
d := conf.RootDomain
if conf.GatewayPort != 443 {
Expand Down
2 changes: 1 addition & 1 deletion gateway/tunnel_http.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package gateway

import (
"context"
"errors"
"fmt"
"net"
"net/http"
Expand All @@ -13,7 +14,6 @@ import (
"github.com/zllovesuki/t/profiler"
"github.com/zllovesuki/t/shared"

"github.com/pkg/errors"
"go.uber.org/zap"
)

Expand Down
Loading

0 comments on commit cfc8ec7

Please sign in to comment.