232 lines
5.9 KiB
Go
232 lines
5.9 KiB
Go
package main
|
|
|
|
import (
|
|
"crypto/sha256"
|
|
"crypto/subtle"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"os"
|
|
"os/user"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
maxEnrollments = 8
|
|
enrollBurst = 6
|
|
enrollRefillPerSecond = 1.0
|
|
)
|
|
|
|
type enrollment struct {
|
|
TokenSHA256 string `json:"token_sha256"`
|
|
Expires int64 `json:"expires"`
|
|
}
|
|
|
|
func enrollmentPath(cfg config) string {
|
|
return filepath.Join(filepath.Dir(cfg.KeyFile), "enrollment.json")
|
|
}
|
|
|
|
func readEnrollments(path string) ([]enrollment, error) {
|
|
data, err := os.ReadFile(path)
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
return nil, nil
|
|
}
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
var items []enrollment
|
|
if err := json.Unmarshal(data, &items); err != nil {
|
|
return nil, err
|
|
}
|
|
return items, nil
|
|
}
|
|
|
|
func writeEnrollments(path string, items []enrollment) error {
|
|
data, err := json.Marshal(items)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := atomicWrite(path, data, 0o600); err != nil {
|
|
return err
|
|
}
|
|
if os.Geteuid() == 0 {
|
|
if serviceUser, err := user.Lookup("rustproxy-docker-agent"); err == nil {
|
|
uid, _ := strconv.Atoi(serviceUser.Uid)
|
|
gid, _ := strconv.Atoi(serviceUser.Gid)
|
|
_ = os.Chown(path, uid, gid)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func hashToken(token string) string {
|
|
sum := sha256.Sum256([]byte(token))
|
|
return hex.EncodeToString(sum[:])
|
|
}
|
|
|
|
func createEnrollment(cfg config, ttl time.Duration, now time.Time) (string, time.Time, error) {
|
|
if ttl < time.Minute || ttl > 7*24*time.Hour {
|
|
return "", time.Time{}, errors.New("enrollment code lifetime must be between 1m and 168h")
|
|
}
|
|
token, err := makeToken()
|
|
if err != nil {
|
|
return "", time.Time{}, err
|
|
}
|
|
path := enrollmentPath(cfg)
|
|
items, err := readEnrollments(path)
|
|
if err != nil {
|
|
return "", time.Time{}, err
|
|
}
|
|
fresh := items[:0]
|
|
for _, item := range items {
|
|
if item.Expires > now.Unix() {
|
|
fresh = append(fresh, item)
|
|
}
|
|
}
|
|
if len(fresh) >= maxEnrollments {
|
|
fresh = fresh[len(fresh)-maxEnrollments+1:]
|
|
}
|
|
expires := now.Add(ttl)
|
|
fresh = append(fresh, enrollment{TokenSHA256: hashToken(token), Expires: expires.Unix()})
|
|
if err := writeEnrollments(path, fresh); err != nil {
|
|
return "", time.Time{}, err
|
|
}
|
|
return token, expires, nil
|
|
}
|
|
|
|
type enroller struct {
|
|
mu sync.Mutex
|
|
}
|
|
|
|
func (e *enroller) redeem(cfg config, presented string, now time.Time) bool {
|
|
e.mu.Lock()
|
|
defer e.mu.Unlock()
|
|
path := enrollmentPath(cfg)
|
|
items, err := readEnrollments(path)
|
|
if err != nil || presented == "" {
|
|
return false
|
|
}
|
|
want := hashToken(presented)
|
|
matched := -1
|
|
kept := make([]enrollment, 0, len(items))
|
|
for index, item := range items {
|
|
if item.Expires <= now.Unix() {
|
|
continue
|
|
}
|
|
if matched < 0 && subtle.ConstantTimeCompare([]byte(item.TokenSHA256), []byte(want)) == 1 {
|
|
matched = index
|
|
continue
|
|
}
|
|
kept = append(kept, item)
|
|
}
|
|
if matched < 0 {
|
|
return false
|
|
}
|
|
if err := writeEnrollments(path, kept); err != nil {
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
type enrollLimiter struct {
|
|
mu sync.Mutex
|
|
tokens float64
|
|
last time.Time
|
|
}
|
|
|
|
func (l *enrollLimiter) allow(now time.Time) bool {
|
|
l.mu.Lock()
|
|
defer l.mu.Unlock()
|
|
if l.last.IsZero() {
|
|
l.tokens = enrollBurst
|
|
l.last = now
|
|
}
|
|
if elapsed := now.Sub(l.last).Seconds(); elapsed > 0 {
|
|
l.tokens += elapsed * enrollRefillPerSecond
|
|
if l.tokens > enrollBurst {
|
|
l.tokens = enrollBurst
|
|
}
|
|
l.last = now
|
|
}
|
|
if l.tokens < 1 {
|
|
return false
|
|
}
|
|
l.tokens--
|
|
return true
|
|
}
|
|
|
|
func enrollHandler(cfg config) http.HandlerFunc {
|
|
state := &enroller{}
|
|
limiter := &enrollLimiter{}
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
if !cfg.TLS || cfg.Fingerprint == "" {
|
|
http.Error(w, "enrollment requires HTTPS", http.StatusForbidden)
|
|
return
|
|
}
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
if !limiter.allow(time.Now()) {
|
|
w.Header().Set("Retry-After", "1")
|
|
http.Error(w, "too many enrollment attempts", http.StatusTooManyRequests)
|
|
return
|
|
}
|
|
auth := strings.TrimSpace(r.Header.Get("Authorization"))
|
|
presented, ok := strings.CutPrefix(auth, "Bearer ")
|
|
if !ok || !state.redeem(cfg, strings.TrimSpace(presented), time.Now()) {
|
|
time.Sleep(300 * time.Millisecond)
|
|
http.Error(w, "unknown, expired or used enrollment code", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.Header().Set("Cache-Control", "no-store")
|
|
_ = json.NewEncoder(w).Encode(map[string]string{"token": cfg.Token, "certificate_sha256": cfg.Fingerprint})
|
|
}
|
|
}
|
|
|
|
type enrollmentPayload struct {
|
|
Version int `json:"v"`
|
|
Name string `json:"name"`
|
|
Endpoint string `json:"endpoint"`
|
|
Enroll string `json:"enroll"`
|
|
Fingerprint string `json:"fingerprint"`
|
|
Expires int64 `json:"expires"`
|
|
Agent string `json:"agent"`
|
|
}
|
|
|
|
func enrollmentCode(cfg config, hostOverride string, ttl time.Duration, now time.Time) (string, time.Time, error) {
|
|
if !cfg.TLS {
|
|
return "", time.Time{}, errors.New("one-time codes require HTTPS; use --static with plain HTTP")
|
|
}
|
|
if !validToken(cfg.Token) {
|
|
return "", time.Time{}, errors.New("no valid token configured; run 'sudo rustproxy-docker-agent init'")
|
|
}
|
|
endpoint, err := provisionEndpoint(cfg, hostOverride)
|
|
if err != nil {
|
|
return "", time.Time{}, err
|
|
}
|
|
fingerprint, err := certificateFingerprint(cfg.CertFile)
|
|
if err != nil {
|
|
return "", time.Time{}, fmt.Errorf("TLS certificate: %w (run 'sudo rustproxy-docker-agent init')", err)
|
|
}
|
|
token, expires, err := createEnrollment(cfg, ttl, now)
|
|
if err != nil {
|
|
return "", time.Time{}, err
|
|
}
|
|
raw, err := json.Marshal(enrollmentPayload{Version: 2, Name: cfg.Hostname, Endpoint: endpoint, Enroll: token,
|
|
Fingerprint: strings.ToLower(strings.ReplaceAll(fingerprint, ":", "")), Expires: expires.Unix(), Agent: version})
|
|
if err != nil {
|
|
return "", time.Time{}, err
|
|
}
|
|
return provisionPrefix + base64.RawURLEncoding.EncodeToString(raw), expires, nil
|
|
}
|