Refactor core
This commit is contained in:
+148
@@ -0,0 +1,148 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
|
||||
"github.com/acme-dns/acme-dns/pkg/acmedns"
|
||||
|
||||
"github.com/caddyserver/certmagic"
|
||||
"github.com/julienschmidt/httprouter"
|
||||
"github.com/rs/cors"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
type AcmednsAPI struct {
|
||||
Config *acmedns.AcmeDnsConfig
|
||||
DB acmedns.AcmednsDB
|
||||
Logger *zap.SugaredLogger
|
||||
errChan chan error
|
||||
}
|
||||
|
||||
func Init(config *acmedns.AcmeDnsConfig, db acmedns.AcmednsDB, logger *zap.SugaredLogger, errChan chan error) AcmednsAPI {
|
||||
a := AcmednsAPI{Config: config, DB: db, Logger: logger, errChan: errChan}
|
||||
return a
|
||||
}
|
||||
|
||||
func (a *AcmednsAPI) Start(dnsservers []acmedns.AcmednsNS) {
|
||||
var err error
|
||||
//TODO: do we want to debug log the HTTP server?
|
||||
stderrorlog, err := zap.NewStdLogAt(a.Logger.Desugar(), zap.ErrorLevel)
|
||||
if err != nil {
|
||||
a.errChan <- err
|
||||
return
|
||||
}
|
||||
//legolog.Logger = stderrorlog
|
||||
api := httprouter.New()
|
||||
c := cors.New(cors.Options{
|
||||
AllowedOrigins: a.Config.API.CorsOrigins,
|
||||
AllowedMethods: []string{"GET", "POST"},
|
||||
OptionsPassthrough: false,
|
||||
Debug: a.Config.General.Debug,
|
||||
})
|
||||
if a.Config.General.Debug {
|
||||
// Logwriter for saner log output
|
||||
c.Log = stderrorlog
|
||||
}
|
||||
if !a.Config.API.DisableRegistration {
|
||||
api.POST("/register", a.webRegisterPost)
|
||||
}
|
||||
api.POST("/update", a.Auth(a.webUpdatePost))
|
||||
api.GET("/health", a.healthCheck)
|
||||
|
||||
host := a.Config.API.IP + ":" + a.Config.API.Port
|
||||
|
||||
// TLS specific general settings
|
||||
cfg := &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
|
||||
switch a.Config.API.TLS {
|
||||
case "letsencryptstaging":
|
||||
magic := a.setupTLS(dnsservers)
|
||||
err = magic.ManageAsync(context.Background(), []string{a.Config.General.Domain})
|
||||
if err != nil {
|
||||
a.errChan <- err
|
||||
return
|
||||
}
|
||||
cfg.GetCertificate = magic.GetCertificate
|
||||
|
||||
srv := &http.Server{
|
||||
Addr: host,
|
||||
Handler: c.Handler(api),
|
||||
TLSConfig: cfg,
|
||||
ErrorLog: stderrorlog,
|
||||
}
|
||||
a.Logger.Infow("Listening HTTPS",
|
||||
"host", host,
|
||||
"domain", a.Config.General.Domain)
|
||||
err = srv.ListenAndServeTLS("", "")
|
||||
case "letsencrypt":
|
||||
magic := a.setupTLS(dnsservers)
|
||||
err = magic.ManageAsync(context.Background(), []string{a.Config.General.Domain})
|
||||
if err != nil {
|
||||
a.errChan <- err
|
||||
return
|
||||
}
|
||||
cfg.GetCertificate = magic.GetCertificate
|
||||
srv := &http.Server{
|
||||
Addr: host,
|
||||
Handler: c.Handler(api),
|
||||
TLSConfig: cfg,
|
||||
ErrorLog: stderrorlog,
|
||||
}
|
||||
a.Logger.Infow("Listening HTTPS",
|
||||
"host", host,
|
||||
"domain", a.Config.General.Domain)
|
||||
err = srv.ListenAndServeTLS("", "")
|
||||
case "cert":
|
||||
srv := &http.Server{
|
||||
Addr: host,
|
||||
Handler: c.Handler(api),
|
||||
TLSConfig: cfg,
|
||||
ErrorLog: stderrorlog,
|
||||
}
|
||||
a.Logger.Infow("Listening HTTPS",
|
||||
"host", host,
|
||||
"domain", a.Config.General.Domain)
|
||||
err = srv.ListenAndServeTLS(a.Config.API.TLSCertFullchain, a.Config.API.TLSCertPrivkey)
|
||||
default:
|
||||
a.Logger.Infow("Listening HTTP",
|
||||
"host", host)
|
||||
err = http.ListenAndServe(host, c.Handler(api))
|
||||
}
|
||||
if err != nil {
|
||||
a.errChan <- err
|
||||
}
|
||||
}
|
||||
|
||||
func (a *AcmednsAPI) setupTLS(dnsservers []acmedns.AcmednsNS) *certmagic.Config {
|
||||
provider := NewChallengeProvider(dnsservers)
|
||||
certmagic.Default.Logger = a.Logger.Desugar()
|
||||
storage := certmagic.FileStorage{Path: a.Config.API.ACMECacheDir}
|
||||
|
||||
// Set up certmagic for getting certificate for acme-dns api
|
||||
certmagic.DefaultACME.DNS01Solver = &provider
|
||||
certmagic.DefaultACME.Agreed = true
|
||||
certmagic.DefaultACME.Logger = a.Logger.Desugar()
|
||||
if a.Config.API.TLS == "letsencrypt" {
|
||||
certmagic.DefaultACME.CA = certmagic.LetsEncryptProductionCA
|
||||
} else {
|
||||
certmagic.DefaultACME.CA = certmagic.LetsEncryptStagingCA
|
||||
}
|
||||
certmagic.DefaultACME.Email = a.Config.API.NotificationEmail
|
||||
|
||||
magicConf := certmagic.Default
|
||||
magicConf.Logger = a.Logger.Desugar()
|
||||
magicConf.Storage = &storage
|
||||
magicConf.DefaultServerName = a.Config.General.Domain
|
||||
magicCache := certmagic.NewCache(certmagic.CacheOptions{
|
||||
GetConfigForCert: func(cert certmagic.Certificate) (*certmagic.Config, error) {
|
||||
return &magicConf, nil
|
||||
},
|
||||
Logger: a.Logger.Desugar(),
|
||||
})
|
||||
magic := certmagic.New(magicCache, magicConf)
|
||||
return magic
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/acme-dns/acme-dns/pkg/acmedns"
|
||||
"net"
|
||||
"net/http"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
type key int
|
||||
|
||||
// ACMETxtKey is a context key for ACMETxt struct
|
||||
const ACMETxtKey key = 0
|
||||
|
||||
// Auth middleware for update request
|
||||
func (a *AcmednsAPI) Auth(update httprouter.Handle) httprouter.Handle {
|
||||
return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
|
||||
postData := acmedns.ACMETxt{}
|
||||
userOK := false
|
||||
user, err := a.getUserFromRequest(r)
|
||||
if err == nil {
|
||||
if a.updateAllowedFromIP(r, user) {
|
||||
dec := json.NewDecoder(r.Body)
|
||||
err = dec.Decode(&postData)
|
||||
if err != nil {
|
||||
a.Logger.Errorw("Decoding error",
|
||||
"error", "json_error")
|
||||
}
|
||||
if user.Subdomain == postData.Subdomain {
|
||||
userOK = true
|
||||
} else {
|
||||
a.Logger.Errorw("Subdomain mismatch",
|
||||
"error", "subdomain_mismatch",
|
||||
"name", postData.Subdomain,
|
||||
"expected", user.Subdomain)
|
||||
}
|
||||
} else {
|
||||
a.Logger.Errorw("Update not allowed from IP",
|
||||
"error", "ip_unauthorized")
|
||||
}
|
||||
} else {
|
||||
a.Logger.Errorw("Error while trying to get user",
|
||||
"error", err.Error())
|
||||
}
|
||||
if userOK {
|
||||
// Set user info to the decoded ACMETxt object
|
||||
postData.Username = user.Username
|
||||
postData.Password = user.Password
|
||||
// Set the ACMETxt struct to context to pull in from update function
|
||||
ctx := context.WithValue(r.Context(), ACMETxtKey, postData)
|
||||
update(w, r.WithContext(ctx), p)
|
||||
} else {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_, _ = w.Write(jsonError("forbidden"))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (a *AcmednsAPI) getUserFromRequest(r *http.Request) (acmedns.ACMETxt, error) {
|
||||
uname := r.Header.Get("X-Api-User")
|
||||
passwd := r.Header.Get("X-Api-Key")
|
||||
username, err := getValidUsername(uname)
|
||||
if err != nil {
|
||||
return acmedns.ACMETxt{}, fmt.Errorf("invalid username: %s: %s", uname, err.Error())
|
||||
}
|
||||
if validKey(passwd) {
|
||||
dbuser, err := a.DB.GetByUsername(username)
|
||||
if err != nil {
|
||||
a.Logger.Errorw("Error while trying to get user",
|
||||
"error", err.Error())
|
||||
// To protect against timed side channel (never gonna give you up)
|
||||
correctPassword(passwd, "$2a$10$8JEFVNYYhLoBysjAxe2yBuXrkDojBQBkVpXEQgyQyjn43SvJ4vL36")
|
||||
|
||||
return acmedns.ACMETxt{}, fmt.Errorf("invalid username: %s", uname)
|
||||
}
|
||||
if correctPassword(passwd, dbuser.Password) {
|
||||
return dbuser, nil
|
||||
}
|
||||
return acmedns.ACMETxt{}, fmt.Errorf("invalid password for user %s", uname)
|
||||
}
|
||||
return acmedns.ACMETxt{}, fmt.Errorf("invalid key for user %s", uname)
|
||||
}
|
||||
|
||||
func (a *AcmednsAPI) updateAllowedFromIP(r *http.Request, user acmedns.ACMETxt) bool {
|
||||
if a.Config.API.UseHeader {
|
||||
ips := getIPListFromHeader(r.Header.Get(a.Config.API.HeaderName))
|
||||
return user.AllowedFromList(ips)
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
a.Logger.Errorw("Error while parsing remote address",
|
||||
"error", err.Error(),
|
||||
"remoteaddr", r.RemoteAddr)
|
||||
host = ""
|
||||
}
|
||||
return user.AllowedFrom(host)
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/acme-dns/acme-dns/pkg/acmedns"
|
||||
|
||||
"github.com/mholt/acmez/acme"
|
||||
)
|
||||
|
||||
// ChallengeProvider implements go-acme/lego Provider interface which is used for ACME DNS challenge handling
|
||||
type ChallengeProvider struct {
|
||||
servers []acmedns.AcmednsNS
|
||||
}
|
||||
|
||||
// NewChallengeProvider creates a new instance of ChallengeProvider
|
||||
func NewChallengeProvider(servers []acmedns.AcmednsNS) ChallengeProvider {
|
||||
return ChallengeProvider{servers: servers}
|
||||
}
|
||||
|
||||
// Present is used for making the ACME DNS challenge token available for DNS
|
||||
func (c *ChallengeProvider) Present(ctx context.Context, challenge acme.Challenge) error {
|
||||
for _, s := range c.servers {
|
||||
s.SetOwnAuthKey(challenge.DNS01KeyAuthorization())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CleanUp is called after the run to remove the ACME DNS challenge tokens from DNS records
|
||||
func (c *ChallengeProvider) CleanUp(ctx context.Context, _ acme.Challenge) error {
|
||||
for _, s := range c.servers {
|
||||
s.SetOwnAuthKey("")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Wait is a dummy function as we are just going to be ready to answer the challenge from the get-go
|
||||
func (c *ChallengeProvider) Wait(_ context.Context, _ acme.Challenge) error {
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
// Endpoint used to check the readiness and/or liveness (health) of the server.
|
||||
func (a *AcmednsAPI) healthCheck(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/acme-dns/acme-dns/pkg/acmedns"
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
// RegResponse is a struct for registration response JSON
|
||||
type RegResponse struct {
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
Fulldomain string `json:"fulldomain"`
|
||||
Subdomain string `json:"subdomain"`
|
||||
Allowfrom []string `json:"allowfrom"`
|
||||
}
|
||||
|
||||
func (a *AcmednsAPI) webRegisterPost(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
var regStatus int
|
||||
var reg []byte
|
||||
var err error
|
||||
aTXT := acmedns.ACMETxt{}
|
||||
bdata, _ := io.ReadAll(r.Body)
|
||||
if len(bdata) > 0 {
|
||||
err = json.Unmarshal(bdata, &aTXT)
|
||||
if err != nil {
|
||||
regStatus = http.StatusBadRequest
|
||||
reg = jsonError("malformed_json_payload")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(regStatus)
|
||||
_, _ = w.Write(reg)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Fail with malformed CIDR mask in allowfrom
|
||||
err = aTXT.AllowFrom.IsValid()
|
||||
if err != nil {
|
||||
regStatus = http.StatusBadRequest
|
||||
reg = jsonError("invalid_allowfrom_cidr")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(regStatus)
|
||||
_, _ = w.Write(reg)
|
||||
return
|
||||
}
|
||||
|
||||
// Create new user
|
||||
nu, err := a.DB.Register(aTXT.AllowFrom)
|
||||
if err != nil {
|
||||
errstr := fmt.Sprintf("%v", err)
|
||||
reg = jsonError(errstr)
|
||||
regStatus = http.StatusInternalServerError
|
||||
a.Logger.Errorw("Error in registration",
|
||||
"error", err.Error())
|
||||
} else {
|
||||
a.Logger.Debugw("Created new user",
|
||||
"user", nu.Username.String())
|
||||
regStruct := RegResponse{nu.Username.String(), nu.Password, nu.Subdomain + "." + a.Config.General.Domain, nu.Subdomain, nu.AllowFrom.ValidEntries()}
|
||||
regStatus = http.StatusCreated
|
||||
reg, err = json.Marshal(regStruct)
|
||||
if err != nil {
|
||||
regStatus = http.StatusInternalServerError
|
||||
reg = jsonError("json_error")
|
||||
a.Logger.Errorw("Could not marshal JSON",
|
||||
"error", "json")
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(regStatus)
|
||||
_, _ = w.Write(reg)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/acme-dns/acme-dns/pkg/acmedns"
|
||||
|
||||
"github.com/julienschmidt/httprouter"
|
||||
)
|
||||
|
||||
func (a *AcmednsAPI) webUpdatePost(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
|
||||
var updStatus int
|
||||
var upd []byte
|
||||
// Get user
|
||||
atxt, ok := r.Context().Value(ACMETxtKey).(acmedns.ACMETxt)
|
||||
if !ok {
|
||||
a.Logger.Errorw("Context error",
|
||||
"error", "context")
|
||||
}
|
||||
// NOTE: An invalid subdomain should not happen - the auth handler should
|
||||
// reject POSTs with an invalid subdomain before this handler. Reject any
|
||||
// invalid subdomains anyway as a matter of caution.
|
||||
if !validSubdomain(atxt.Subdomain) {
|
||||
a.Logger.Errorw("Bad update data",
|
||||
"error", "subdomain",
|
||||
"subdomain", atxt.Subdomain,
|
||||
"txt", atxt.Value)
|
||||
updStatus = http.StatusBadRequest
|
||||
upd = jsonError("bad_subdomain")
|
||||
} else if !validTXT(atxt.Value) {
|
||||
a.Logger.Errorw("Bad update data",
|
||||
"error", "txt",
|
||||
"subdomain", atxt.Subdomain,
|
||||
"txt", atxt.Value)
|
||||
updStatus = http.StatusBadRequest
|
||||
upd = jsonError("bad_txt")
|
||||
} else if validSubdomain(atxt.Subdomain) && validTXT(atxt.Value) {
|
||||
err := a.DB.Update(atxt.ACMETxtPost)
|
||||
if err != nil {
|
||||
a.Logger.Errorw("Error while trying to update record",
|
||||
"error", err.Error())
|
||||
updStatus = http.StatusInternalServerError
|
||||
upd = jsonError("db_error")
|
||||
} else {
|
||||
a.Logger.Debugw("TXT record updated",
|
||||
"subdomain", atxt.Subdomain,
|
||||
"txt", atxt.Value)
|
||||
updStatus = http.StatusOK
|
||||
upd = []byte("{\"txt\": \"" + atxt.Value + "\"}")
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(updStatus)
|
||||
_, _ = w.Write(upd)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/acme-dns/acme-dns/pkg/acmedns"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
func jsonError(message string) []byte {
|
||||
return []byte(fmt.Sprintf("{\"error\": \"%s\"}", message))
|
||||
}
|
||||
|
||||
func getValidUsername(u string) (uuid.UUID, error) {
|
||||
uname, err := uuid.Parse(u)
|
||||
if err != nil {
|
||||
return uuid.UUID{}, err
|
||||
}
|
||||
return uname, nil
|
||||
}
|
||||
|
||||
func validKey(k string) bool {
|
||||
kn := acmedns.SanitizeString(k)
|
||||
if utf8.RuneCountInString(k) == 40 && utf8.RuneCountInString(kn) == 40 {
|
||||
// Correct length and all chars valid
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func correctPassword(pw string, hash string) bool {
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(pw)); err == nil {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func getIPListFromHeader(header string) []string {
|
||||
iplist := []string{}
|
||||
for _, v := range strings.Split(header, ",") {
|
||||
if len(v) > 0 {
|
||||
// Ignore empty values
|
||||
iplist = append(iplist, strings.TrimSpace(v))
|
||||
}
|
||||
}
|
||||
return iplist
|
||||
}
|
||||
|
||||
func validSubdomain(s string) bool {
|
||||
// URL safe base64 alphabet without padding as defined in ACME
|
||||
RegExp := regexp.MustCompile("^[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?$")
|
||||
return RegExp.MatchString(s)
|
||||
}
|
||||
|
||||
func validTXT(s string) bool {
|
||||
sn := acmedns.SanitizeString(s)
|
||||
if utf8.RuneCountInString(s) == 43 && utf8.RuneCountInString(sn) == 43 {
|
||||
// 43 chars is the current LE auth key size, but not limited / defined by ACME
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user