Something went wrong. Try again.
An ACME client designed to obtain publicly-trusted SSL/TLS certificates for internal resources.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433package server
import ( "archive/zip" "bytes" "context" "crypto/rand" "crypto/subtle" "encoding/hex" "fmt" "log" "net" "net/http" "strings" "sync" "time"
"github.com/rcsheets/acme-lantern/internal/storage")
// ChallengeServer handles HTTP-01 ACME challengestype ChallengeServer struct { addr string server *http.Server mux *http.ServeMux mu sync.RWMutex tokens map[string]string // token -> key authorization shutdown chan struct{} dashboard *Dashboard lastRenewalRun time.Time lastManualTrigger time.Time RenewalTrigger chan struct{} // Exported for use in main renewal loop manualTriggerLimit time.Duration // Minimum time between manual triggers
// Ephemeral deploy API ephemeralEnabled bool deployToken string deployTokenExpiry time.Time storage *storage.Storage}
// New creates a new ChallengeServerfunc New(addr string) *ChallengeServer { cs := &ChallengeServer{ addr: addr, tokens: make(map[string]string), shutdown: make(chan struct{}), RenewalTrigger: make(chan struct{}, 1), lastRenewalRun: time.Now(), manualTriggerLimit: 5 * time.Minute, // Minimum 5 minutes between manual triggers }
mux := http.NewServeMux() cs.mux = mux
// ACME HTTP-01 challenge handler mux.HandleFunc("/.well-known/acme-challenge/", cs.handleChallenge)
// Health/status endpoint mux.HandleFunc("/health", cs.handleHealth)
// Dashboard routes (will be enabled after SetDashboard is called) mux.HandleFunc("/", cs.handleDashboardRoute) mux.HandleFunc("/add", cs.handleDashboardRoute) mux.HandleFunc("/toggle", cs.handleDashboardRoute) mux.HandleFunc("/delete", cs.handleDashboardRoute) mux.HandleFunc("/trigger-renewal", cs.handleDashboardRoute)
cs.server = &http.Server{ Addr: addr, Handler: mux, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, IdleTimeout: 120 * time.Second, }
return cs}
// EnableEphemeralAPI sets up the temporary token-gated download API.// It generates a random token, stores expiry, and registers handlers.func (cs *ChallengeServer) EnableEphemeralAPI(stor *storage.Storage, ttl time.Duration) error { cs.mu.Lock() defer cs.mu.Unlock()
// Generate 32-byte random token and hex-encode b := make([]byte, 32) if _, err := rand.Read(b); err != nil { return fmt.Errorf("generating deploy token: %w", err) } token := hex.EncodeToString(b)
cs.storage = stor cs.deployToken = token cs.deployTokenExpiry = time.Now().Add(ttl) cs.ephemeralEnabled = true
// Register handlers cs.mux.HandleFunc("/api/deploy/bundle", cs.handleDeployBundle) cs.mux.HandleFunc("/api/deploy/cert", cs.handleDeployCert) cs.mux.HandleFunc("/api/deploy/key", cs.handleDeployKey)
// Log instructions log.Printf("Ephemeral deploy API enabled. Token expires at %s", cs.deployTokenExpiry.Format(time.RFC3339)) log.Printf("Use the token to download bundles from RFC1918 addresses only. Example:") log.Printf(" curl -fsS 'http://localhost%[1]s/api/deploy/bundle?domain=example.com&token=%[2]s' -o example.com-bundle.zip", cs.addr, token) log.Printf("Or individually:") log.Printf(" curl -fsS 'http://localhost%[1]s/api/deploy/cert?domain=example.com&token=%[2]s' -o fullchain.pem", cs.addr, token) log.Printf(" curl -fsS 'http://localhost%[1]s/api/deploy/key?domain=example.com&token=%[2]s' -o privkey.pem", cs.addr, token)
return nil}
// validateDeployRequest checks RFC1918, token presence and expiry.func (cs *ChallengeServer) validateDeployRequest(w http.ResponseWriter, r *http.Request) bool { // RFC1918 check allowed, reason := isRFC1918Address(r.RemoteAddr) if !allowed { log.Printf("Deploy API access denied: %s | Method: %s | URI: %s | Remote: %s", reason, r.Method, r.RequestURI, r.RemoteAddr) http.Error(w, "Forbidden", http.StatusForbidden) return false }
// Token check token := r.URL.Query().Get("token") if token == "" { http.Error(w, "Forbidden", http.StatusForbidden) return false }
cs.mu.RLock() expected := cs.deployToken expiry := cs.deployTokenExpiry enabled := cs.ephemeralEnabled cs.mu.RUnlock()
if !enabled || time.Now().After(expiry) { http.Error(w, "Forbidden", http.StatusForbidden) return false }
if subtle.ConstantTimeCompare([]byte(token), []byte(expected)) != 1 { http.Error(w, "Forbidden", http.StatusForbidden) return false } return true}
func (cs *ChallengeServer) handleDeployBundle(w http.ResponseWriter, r *http.Request) { if !cs.validateDeployRequest(w, r) { return } domain := r.URL.Query().Get("domain") if domain == "" { http.Error(w, "Bad Request: missing domain", http.StatusBadRequest) return }
certPEM, err := cs.storage.LoadCertificate([]string{domain}) if err != nil { http.Error(w, "Not Found", http.StatusNotFound) return } keyPEM, err := cs.storage.LoadPrivateKey([]string{domain}) if err != nil { http.Error(w, "Not Found", http.StatusNotFound) return }
buf := &bytes.Buffer{} zw := zip.NewWriter(buf) // Add files if f, err := zw.Create("fullchain.pem"); err == nil { _, _ = f.Write(certPEM) } else { _ = zw.Close() http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } if f, err := zw.Create("privkey.pem"); err == nil { _, _ = f.Write(keyPEM) } else { _ = zw.Close() http.Error(w, "Internal Server Error", http.StatusInternalServerError) return } if err := zw.Close(); err != nil { http.Error(w, "Internal Server Error", http.StatusInternalServerError) return }
filename := sanitizeForFilename(domain) + "-bundle.zip" w.Header().Set("Content-Type", "application/zip") w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", filename)) _, _ = w.Write(buf.Bytes())}
func (cs *ChallengeServer) handleDeployCert(w http.ResponseWriter, r *http.Request) { if !cs.validateDeployRequest(w, r) { return } domain := r.URL.Query().Get("domain") if domain == "" { http.Error(w, "Bad Request: missing domain", http.StatusBadRequest) return } certPEM, err := cs.storage.LoadCertificate([]string{domain}) if err != nil { http.Error(w, "Not Found", http.StatusNotFound) return } w.Header().Set("Content-Type", "application/x-pem-file") _, _ = w.Write(certPEM)}
func (cs *ChallengeServer) handleDeployKey(w http.ResponseWriter, r *http.Request) { if !cs.validateDeployRequest(w, r) { return } domain := r.URL.Query().Get("domain") if domain == "" { http.Error(w, "Bad Request: missing domain", http.StatusBadRequest) return } keyPEM, err := cs.storage.LoadPrivateKey([]string{domain}) if err != nil { http.Error(w, "Not Found", http.StatusNotFound) return } w.Header().Set("Content-Type", "application/x-pem-file") _, _ = w.Write(keyPEM)}
// sanitizeForFilename converts domain to a safe filename componentfunc sanitizeForFilename(domain string) string { // replace wildcard and dots s := domain s = strings.ReplaceAll(s, "*", "wildcard") s = strings.ReplaceAll(s, ".", "_") return s}
// SetDashboard configures the dashboard for the serverfunc (cs *ChallengeServer) SetDashboard(dashboard *Dashboard) { cs.dashboard = dashboard}
// handleDashboardRoute routes dashboard requests to appropriate handlersfunc (cs *ChallengeServer) handleDashboardRoute(w http.ResponseWriter, r *http.Request) { if cs.dashboard == nil { http.NotFound(w, r) return }
switch r.URL.Path { case "/": cs.dashboard.HandleDashboard(w, r) case "/add": cs.dashboard.HandleAddCert(w, r) case "/toggle": cs.dashboard.HandleToggleCert(w, r) case "/delete": cs.dashboard.HandleDeleteCert(w, r) case "/trigger-renewal": cs.dashboard.HandleTriggerRenewal(w, r) default: http.NotFound(w, r) }}
// GetRenewalStatus returns information about the renewal loopfunc (cs *ChallengeServer) GetRenewalStatus(checkInterval int) (lastRun time.Time, nextRun time.Time, timeUntilNext time.Duration) { cs.mu.RLock() defer cs.mu.RUnlock()
lastRun = cs.lastRenewalRun nextRun = lastRun.Add(time.Duration(checkInterval) * time.Hour) timeUntilNext = time.Until(nextRun) return}
// TriggerRenewal sends a signal to trigger the renewal loop immediately// Returns true if trigger was sent, false if rate limited// Returns the time remaining until the next trigger is allowed if rate limitedfunc (cs *ChallengeServer) TriggerRenewal() (bool, time.Duration) { cs.mu.Lock() defer cs.mu.Unlock()
// Check if enough time has passed since last manual trigger timeSince := time.Since(cs.lastManualTrigger) if timeSince < cs.manualTriggerLimit { timeRemaining := cs.manualTriggerLimit - timeSince log.Printf("Manual renewal trigger rate limited (last trigger: %v ago, %v remaining)", timeSince.Round(time.Second), timeRemaining.Round(time.Second)) return false, timeRemaining }
select { case cs.RenewalTrigger <- struct{}{}: cs.lastManualTrigger = time.Now() log.Println("Manual renewal triggered from dashboard") return true, 0 default: // Channel is full, renewal already triggered log.Println("Manual renewal trigger already pending") return false, 0 }}
// UpdateLastRenewalRun updates the timestamp of the last renewal runfunc (cs *ChallengeServer) UpdateLastRenewalRun() { cs.mu.Lock() defer cs.mu.Unlock() cs.lastRenewalRun = time.Now()}
// Start begins listening for HTTP requestsfunc (cs *ChallengeServer) Start() error { log.Printf("Starting HTTP server on %s", cs.addr)
go func() { if err := cs.server.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Printf("HTTP server error: %v", err) } }()
return nil}
// Stop gracefully shuts down the serverfunc (cs *ChallengeServer) Stop(ctx context.Context) error { log.Println("Shutting down HTTP server") close(cs.shutdown) return cs.server.Shutdown(ctx)}
// SetToken registers a challenge token and its key authorizationfunc (cs *ChallengeServer) SetToken(token, keyAuth string) { cs.mu.Lock() defer cs.mu.Unlock() cs.tokens[token] = keyAuth log.Printf("Registered challenge token: %s", token)}
// ClearToken removes a challenge tokenfunc (cs *ChallengeServer) ClearToken(token string) { cs.mu.Lock() defer cs.mu.Unlock() delete(cs.tokens, token) log.Printf("Cleared challenge token: %s", token)}
// handleChallenge responds to ACME HTTP-01 challenge requestsfunc (cs *ChallengeServer) handleChallenge(w http.ResponseWriter, r *http.Request) { // Extract token from URL path // Path format: /.well-known/acme-challenge/{token} token := r.URL.Path[len("/.well-known/acme-challenge/"):]
if token == "" { http.NotFound(w, r) return }
cs.mu.RLock() keyAuth, exists := cs.tokens[token] cs.mu.RUnlock()
if !exists { log.Printf("Challenge request for unknown token: %s", token) http.NotFound(w, r) return }
log.Printf("Responding to challenge for token: %s", token) w.Header().Set("Content-Type", "text/plain") fmt.Fprint(w, keyAuth)}
// handleHealth responds to health check requestsfunc (cs *ChallengeServer) handleHealth(w http.ResponseWriter, r *http.Request) { // Only allow access from RFC1918 private addresses allowed, reason := isRFC1918Address(r.RemoteAddr) if !allowed { log.Printf("Health check access denied: %s | Method: %s | URI: %s | User-Agent: %s | Remote: %s", reason, r.Method, r.RequestURI, r.UserAgent(), r.RemoteAddr) http.Error(w, "Forbidden", http.StatusForbidden) return }
w.Header().Set("Content-Type", "application/json") fmt.Fprintf(w, `{"status":"ok","service":"acme-lantern"}`)}
// isRFC1918Address checks if the remote address is from RFC1918 private networks// Returns true if allowed, and a description of the resultfunc isRFC1918Address(remoteAddr string) (bool, string) { // Extract IP from "IP:port" format host, _, err := net.SplitHostPort(remoteAddr) if err != nil { // If no port, treat the whole string as IP host = remoteAddr }
ip := net.ParseIP(host) if ip == nil { return false, fmt.Sprintf("invalid IP address: %s", host) }
// RFC1918 private address ranges: // 10.0.0.0/8 // 172.16.0.0/12 // 192.168.0.0/16 // Also include localhost rfc1918Ranges := map[string]string{ "10.0.0.0/8": "RFC1918 Class A private", "172.16.0.0/12": "RFC1918 Class B private", "192.168.0.0/16": "RFC1918 Class C private", "127.0.0.0/8": "IPv4 localhost", "::1/128": "IPv6 localhost", }
for cidr, description := range rfc1918Ranges { _, network, err := net.ParseCIDR(cidr) if err != nil { continue } if network.Contains(ip) { return true, fmt.Sprintf("%s in %s (%s)", ip, cidr, description) } }
return false, fmt.Sprintf("public IP address %s (not in RFC1918 ranges)", ip)}