This upgrades the Masyunis fork from Anubis v1.25.0 to the latest stable release, **v1.28.2** (“Wuk Lamat Echo 2”), while keeping the fork’s custom styling and removals. ## Approach The Gitea repo is a tree snapshot of v1.25.0, not a git-level fork of [TecharoHQ/anubis](https://github.com/TecharoHQ/anubis). The histories share no commits, so a merge or rebase onto the upstream tag is not usable. The first commit on this branch replaces the tree with a snapshot of the **v1.28.2** tag (`git rm -r` plus `git checkout v1.28.2 -- .`; the import tree is identical to the tag). A short patch series on top restores the Masyunis customizations. ## Customizations kept - Masyunya mascots (`web/static/img/{happy,pensive,reject}.webp`), hashes match current `master`. - `web/static/img/ATTRIBUTIONS.txt` stays deleted. - Challenge footer: drop the `made_with` (Canada / maple-leaf) line and the CELPHASE mascot credit; keep “Protected by Anubis from Techaro”. The generated `web/index_templ.go` matches `go generate ./web`. - Short README (the old `anubisc` typo is fixed). - Version stamped `v1.28.2/masyunis` via Makefile ldflags. `anubis.go` `init()` does not overwrite a link-time version; `go run` / `go test` still report `devel` on purpose. - Upstream `.github`, `.devcontainer`, `.husky`, and `.vscode` stay deleted. - `"uk"` is removed from `lib/localization/locales/manifest.json` **on purpose**, because of Alpine locale problems. `uk.json` and its test entry stay; the served manifest lists 27 languages. - `package.json` `prepare` no longer runs `husky` (the hooks directory is gone). The rest of the script is unchanged. `husky` remains in devDependencies, as upstream left it. ## Deploy notes - **Cookie rename (v1.27):** with the default `DYNAMIC_COOKIE_SUFFIX=true`, cookie names become e.g. `techaro.lol-anubis-auth-<hash>`. Existing clients get a **one-time re-challenge**. That is expected, not a loop. - **Docker / ko / yeet builds** skip the Makefile ldflags, so the displayed version is `<git-version>/masyunis`. It is `v1.28.2/masyunis` only when built from a `v1.28.2` tag (or via `make build` / `make prebaked-build`). - Go 1.27.3 is required (upstream bump in v1.28.2). Thoth (`THOTH_URL` / `THOTH_TOKEN`) was removed upstream; those settings now warn and do nothing. New WASM challenge methods stay disabled unless opted in. ## Verification - `make build` succeeds. `./var/anubis --version` prints `Anubis v1.28.2/masyunis`. - `SKIP_INTEGRATION=1 go test ./...` passes (unit tests; integration package is skipped). - Local challenge/reject pages (en and ru) show Masyunya, version `v1.28.2/masyunis`, and no Canada / CELPHASE / mascot-credit text. Screenshots:   - Upstream Playwright tests (`make test` without `SKIP_INTEGRATION`) fail on this box because the browser download fails. A clean v1.28.2 tree fails the same three Playwright tests here, so this is not a fork regression. - `npm audit` reports **4** findings in upstream’s lockfile (2 moderate, 2 high: `brace-expansion`, `fast-uri`, `lodash.trim`, `source-map-js`). Left alone. Please review and merge when ready. I will not merge this myself. Reviewed-on: #1 Co-authored-by: Lead <3+lead_bot@noreply.git.unvr.site>
551 lines
22 KiB
Go
551 lines
22 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/ed25519"
|
|
"crypto/rand"
|
|
"crypto/tls"
|
|
"embed"
|
|
"encoding/hex"
|
|
"errors"
|
|
"flag"
|
|
"fmt"
|
|
"io/fs"
|
|
"log"
|
|
"log/slog"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httputil"
|
|
"net/url"
|
|
"os"
|
|
"os/signal"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/TecharoHQ/anubis"
|
|
"github.com/TecharoHQ/anubis/data"
|
|
"github.com/TecharoHQ/anubis/internal"
|
|
libanubis "github.com/TecharoHQ/anubis/lib"
|
|
"github.com/TecharoHQ/anubis/lib/config"
|
|
"github.com/TecharoHQ/anubis/lib/metrics"
|
|
botPolicy "github.com/TecharoHQ/anubis/lib/policy"
|
|
"github.com/TecharoHQ/anubis/web"
|
|
"github.com/facebookgo/flagenv"
|
|
"github.com/google/uuid"
|
|
_ "github.com/joho/godotenv/autoload"
|
|
healthv1 "google.golang.org/grpc/health/grpc_health_v1"
|
|
)
|
|
|
|
var (
|
|
basePrefix = flag.String("base-prefix", "", "base prefix (root URL) the application is served under e.g. /myapp")
|
|
bind = flag.String("bind", ":8923", "network address to bind HTTP to")
|
|
bindNetwork = flag.String("bind-network", "tcp", "network family to bind HTTP to, e.g. unix, tcp")
|
|
challengeDifficulty = flag.Int("difficulty", anubis.DefaultDifficulty, "difficulty of the challenge")
|
|
cookieDomain = flag.String("cookie-domain", "", "if set, the top-level domain that the Anubis cookie will be valid for")
|
|
cookieDynamicDomain = flag.Bool("cookie-dynamic-domain", false, "if set, automatically set the cookie Domain value based on the request domain")
|
|
cookieExpiration = flag.Duration("cookie-expiration-time", anubis.CookieDefaultExpirationTime, "The amount of time the authorization cookie is valid for")
|
|
cookiePrefix = flag.String("cookie-prefix", anubis.CookieName, "prefix for browser cookies created by Anubis")
|
|
cookiePartitioned = flag.Bool("cookie-partitioned", true, "if true, sets the partitioned flag on Anubis cookies, enabling CHIPS support")
|
|
dynamicCookieSuffix = flag.Bool("dynamic-cookie-suffix", true, "if true, generates a suffix for cookie names based on cookie settings")
|
|
difficultyInJWT = flag.Bool("difficulty-in-jwt", false, "if true, adds a difficulty field in the JWT claims")
|
|
useSimplifiedExplanation = flag.Bool("use-simplified-explanation", true, "deprecated: has no effect, the simplified explanation is always used")
|
|
forcedLanguage = flag.String("forced-language", "", "if set, this language is being used instead of the one from the request's Accept-Language header")
|
|
hs512Secret = flag.String("hs512-secret", "", "secret used to sign JWTs, uses ed25519 if not set")
|
|
cookieSecure = flag.Bool("cookie-secure", true, "if true, sets the secure flag on Anubis cookies")
|
|
cookieHttpOnly = flag.Bool("cookie-http-only", false, "if true, sets the HttpOnly flag on Anubis cookies")
|
|
cookieSameSite = flag.String("cookie-same-site", "None", "sets the same site option on Anubis cookies, will auto-downgrade None to Lax if cookie-secure is false. Valid values are None, Lax, Strict, and Default.")
|
|
ed25519PrivateKeyHex = flag.String("ed25519-private-key-hex", "", "private key used to sign JWTs, if not set a random one will be assigned")
|
|
ed25519PrivateKeyHexFile = flag.String("ed25519-private-key-hex-file", "", "file name containing value for ed25519-private-key-hex")
|
|
metricsBind = flag.String("metrics-bind", ":9090", "network address to bind metrics to")
|
|
metricsBindNetwork = flag.String("metrics-bind-network", "tcp", "network family for the metrics server to bind to")
|
|
socketMode = flag.String("socket-mode", "0770", "socket mode (permissions) for unix domain sockets.")
|
|
robotsTxt = flag.Bool("serve-robots-txt", false, "serve a robots.txt file that disallows all robots")
|
|
policyFname = flag.String("policy-fname", "", "full path to anubis policy document (defaults to a sensible built-in policy)")
|
|
redirectDomains = flag.String("redirect-domains", "", "list of domains separated by commas which anubis is allowed to redirect to. Leaving this unset allows any domain.")
|
|
slogLevel = flag.String("slog-level", "INFO", "logging level (see https://pkg.go.dev/log/slog#hdr-Levels)")
|
|
stripBasePrefix = flag.Bool("strip-base-prefix", false, "if true, strips the base prefix from requests forwarded to the target server")
|
|
target = flag.String("target", "http://localhost:3923", "target to reverse proxy to, set to an empty string to disable proxying when only using auth request")
|
|
targetSNI = flag.String("target-sni", "", "if set, TLS handshake hostname when forwarding requests to the target, if set to auto, use Host header")
|
|
targetHost = flag.String("target-host", "", "if set, the value of the Host header when forwarding requests to the target")
|
|
targetInsecureSkipVerify = flag.Bool("target-insecure-skip-verify", false, "if true, skips TLS validation for the backend")
|
|
targetDisableKeepAlive = flag.Bool("target-disable-keepalive", false, "if true, disables HTTP keep-alive for the backend")
|
|
healthcheck = flag.Bool("healthcheck", false, "run a health check against Anubis")
|
|
useRemoteAddress = flag.Bool("use-remote-address", false, "read the client's IP address from the network request, useful for debugging and running Anubis on bare metal")
|
|
debugBenchmarkJS = flag.Bool("debug-benchmark-js", false, "respond to every request with a challenge for benchmarking hashrate")
|
|
ogPassthrough = flag.Bool("og-passthrough", false, "enable Open Graph tag passthrough")
|
|
ogTimeToLive = flag.Duration("og-expiry-time", 24*time.Hour, "Open Graph tag cache expiration time")
|
|
ogCacheConsiderHost = flag.Bool("og-cache-consider-host", false, "enable or disable the use of the host in the Open Graph tag cache")
|
|
extractResources = flag.String("extract-resources", "", "if set, extract the static resources to the specified folder")
|
|
webmasterEmail = flag.String("webmaster-email", "", "if set, displays webmaster's email on the reject page for appeals")
|
|
versionFlag = flag.Bool("version", false, "print Anubis version")
|
|
publicUrl = flag.String("public-url", "", "the externally accessible URL for this Anubis instance, used for constructing redirect URLs (e.g., for forwardAuth).")
|
|
xffStripPrivate = flag.Bool("xff-strip-private", true, "if set, strip private addresses from X-Forwarded-For")
|
|
customRealIPHeader = flag.String("custom-real-ip-header", "", "if set, read remote IP from header of this name (in case your environment doesn't set X-Real-IP header)")
|
|
|
|
thothInsecure = flag.Bool("thoth-insecure", false, "deprecated: Thoth support was removed, use the geoip block in the policy file")
|
|
thothURL = flag.String("thoth-url", "", "deprecated: Thoth support was removed, use the geoip block in the policy file")
|
|
thothToken = flag.String("thoth-token", "", "deprecated: Thoth support was removed, use the geoip block in the policy file")
|
|
jwtRestrictionHeader = flag.String("jwt-restriction-header", "X-Real-IP", "If set, the JWT is only valid if the current value of this header matched the value when the JWT was created")
|
|
|
|
preserveRefererQueryParam = flag.Bool("preserve-referer-query-param", false, "if true, appends the original external Referer host as utm_source/utm_medium query parameters to the post-challenge redirect URL, for analytics tools that rely on document.referrer or UTM tags instead of the HTTP Referer header. See https://github.com/TecharoHQ/anubis/issues/1596")
|
|
)
|
|
|
|
func keyFromHex(value string) (ed25519.PrivateKey, error) {
|
|
keyBytes, err := hex.DecodeString(value)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("supplied key is not hex-encoded: %w", err)
|
|
}
|
|
|
|
if len(keyBytes) != ed25519.SeedSize {
|
|
return nil, fmt.Errorf("supplied key is not %d bytes long, got %d bytes", ed25519.SeedSize, len(keyBytes))
|
|
}
|
|
|
|
return ed25519.NewKeyFromSeed(keyBytes), nil
|
|
}
|
|
|
|
func doHealthCheck() error {
|
|
resp, err := http.Get("http://localhost" + *metricsBind + "/healthz")
|
|
if err != nil {
|
|
return fmt.Errorf("failed to fetch metrics: %w", err)
|
|
}
|
|
defer resp.Body.Close() //nolint:errcheck
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func parseSameSite(s string) http.SameSite {
|
|
switch strings.ToLower(s) {
|
|
case "none":
|
|
return http.SameSiteNoneMode
|
|
case "lax":
|
|
return http.SameSiteLaxMode
|
|
case "strict":
|
|
return http.SameSiteStrictMode
|
|
case "default":
|
|
return http.SameSiteDefaultMode
|
|
default:
|
|
log.Fatalf("invalid cookie same-site mode: %s, valid values are None, Lax, Strict, and Default", s)
|
|
}
|
|
return http.SameSiteDefaultMode
|
|
}
|
|
|
|
func makeReverseProxy(target string, targetSNI string, targetHost string, insecureSkipVerify bool, targetDisableKeepAlive bool) (http.Handler, error) {
|
|
targetUri, err := url.Parse(target)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to parse target URL: %w", err)
|
|
}
|
|
|
|
transport := http.DefaultTransport.(*http.Transport).Clone()
|
|
|
|
if targetDisableKeepAlive {
|
|
transport.DisableKeepAlives = true
|
|
}
|
|
|
|
// https://github.com/oauth2-proxy/oauth2-proxy/blob/4e2100a2879ef06aea1411790327019c1a09217c/pkg/upstream/http.go#L124
|
|
if targetUri.Scheme == "unix" {
|
|
// clean path up so we don't use the socket path in proxied requests
|
|
addr := targetUri.Path
|
|
targetUri.Path = ""
|
|
// tell transport how to dial unix sockets
|
|
transport.DialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
|
|
dialer := net.Dialer{}
|
|
return dialer.DialContext(ctx, "unix", addr)
|
|
}
|
|
// tell transport how to handle the unix url scheme
|
|
transport.RegisterProtocol("unix", libanubis.UnixRoundTripper{Transport: transport})
|
|
}
|
|
|
|
if insecureSkipVerify || targetSNI != "" {
|
|
transport.TLSClientConfig = &tls.Config{}
|
|
}
|
|
if insecureSkipVerify {
|
|
slog.Warn("TARGET_INSECURE_SKIP_VERIFY is set to true, TLS certificate validation will not be performed", "target", target)
|
|
transport.TLSClientConfig.InsecureSkipVerify = true
|
|
}
|
|
if targetSNI != "" && targetSNI != "auto" {
|
|
transport.TLSClientConfig.ServerName = targetSNI
|
|
}
|
|
|
|
rp := &httputil.ReverseProxy{
|
|
Transport: transport,
|
|
Rewrite: func(r *httputil.ProxyRequest) {
|
|
r.SetURL(targetUri)
|
|
// SetURL clears Out.Host; preserve the inbound Host, matching the
|
|
// previous NewSingleHostReverseProxy default.
|
|
r.Out.Host = r.In.Host
|
|
|
|
// Rewrite mode re-encodes the outbound query through
|
|
// url.ParseQuery, which silently drops ';'-separated parameters.
|
|
// Some upstreams (notably gitweb: /?p=repo.git;a=summary) use ';'
|
|
// as a query separator, so restore the client's raw query verbatim
|
|
// to match the previous NewSingleHostReverseProxy behavior.
|
|
// This fixes https://github.com/TecharoHQ/anubis/issues/1763.
|
|
if tq := targetUri.RawQuery; tq == "" || r.In.URL.RawQuery == "" {
|
|
r.Out.URL.RawQuery = tq + r.In.URL.RawQuery
|
|
} else {
|
|
r.Out.URL.RawQuery = tq + "&" + r.In.URL.RawQuery
|
|
}
|
|
|
|
// Rewrite mode strips forwarding headers before this runs. Anubis
|
|
// sets these upstream (see internal/headers.go XForwardedForUpdate),
|
|
// so copy them through unchanged so the target still sees them.
|
|
for _, h := range []string{"Forwarded", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto"} {
|
|
if v, ok := r.In.Header[h]; ok {
|
|
r.Out.Header[h] = v
|
|
}
|
|
}
|
|
|
|
if targetHost != "" {
|
|
r.Out.Host = targetHost
|
|
}
|
|
|
|
},
|
|
}
|
|
|
|
if targetSNI == "auto" {
|
|
rp.Transport = automaticSNITransport{transport}
|
|
}
|
|
return rp, nil
|
|
}
|
|
|
|
type automaticSNITransport struct{ transport *http.Transport }
|
|
|
|
func (t automaticSNITransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
|
transport := t.transport.Clone()
|
|
transport.TLSClientConfig = t.transport.TLSClientConfig.Clone()
|
|
host := r.Host
|
|
if hostname, _, err := net.SplitHostPort(host); err == nil {
|
|
host = hostname
|
|
}
|
|
transport.TLSClientConfig.ServerName = host
|
|
transport.DisableKeepAlives = true
|
|
return transport.RoundTrip(r)
|
|
}
|
|
|
|
func main() {
|
|
platformStartup()
|
|
|
|
flagenv.Parse()
|
|
flag.Parse()
|
|
|
|
// Must be set before any concurrent UUID call.
|
|
uuid.EnableRandPool()
|
|
|
|
if *versionFlag {
|
|
fmt.Println("Anubis", anubis.Version)
|
|
return
|
|
}
|
|
|
|
if handleBootstrapFlag() {
|
|
return
|
|
}
|
|
|
|
if *healthcheck {
|
|
log.Println("running healthcheck")
|
|
if err := doHealthCheck(); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
return
|
|
}
|
|
|
|
if *extractResources != "" {
|
|
if err := extractEmbedFS(data.BotPolicies, ".", filepath.Join(*extractResources, "data")); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
if err := extractEmbedFS(web.Static, "static", *extractResources); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
fmt.Printf("Extracted embedded static files to %s\n", *extractResources)
|
|
return
|
|
}
|
|
|
|
if runPlatformService(run) {
|
|
return
|
|
}
|
|
|
|
// install signal handler
|
|
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
run(ctx)
|
|
}
|
|
|
|
// run starts Anubis and blocks until ctx is cancelled or the server stops.
|
|
func run(ctx context.Context) {
|
|
internal.SetHealth("anubis", healthv1.HealthCheckResponse_NOT_SERVING)
|
|
|
|
lg := internal.InitSlog(*slogLevel, os.Stderr)
|
|
lg.InfoContext(ctx, "starting up Anubis")
|
|
|
|
wg := new(sync.WaitGroup)
|
|
|
|
var rp http.Handler
|
|
// when using anubis via Systemd and environment variables, then it is not possible to set targe to an empty string but only to space
|
|
if strings.TrimSpace(*target) != "" {
|
|
var err error
|
|
rp, err = makeReverseProxy(*target, *targetSNI, *targetHost, *targetInsecureSkipVerify, *targetDisableKeepAlive)
|
|
if err != nil {
|
|
log.Fatalf("can't make reverse proxy: %v", err)
|
|
}
|
|
}
|
|
|
|
if *cookieDomain != "" && *cookieDynamicDomain {
|
|
log.Fatalf("you can't set COOKIE_DOMAIN and COOKIE_DYNAMIC_DOMAIN at the same time")
|
|
}
|
|
|
|
if *thothURL != "" || *thothToken != "" || *thothInsecure {
|
|
lg.WarnContext(ctx, "Thoth support was removed and THOTH_URL, THOTH_TOKEN, and THOTH_INSECURE are ignored. Use the geoip block in your policy file for asns and geoip rules instead")
|
|
}
|
|
|
|
lg.InfoContext(ctx, "loading policy file", "fname", *policyFname)
|
|
policy, err := libanubis.LoadPoliciesOrDefault(ctx, *policyFname, *challengeDifficulty, *slogLevel, strings.TrimSpace(*target) == "")
|
|
if err != nil {
|
|
log.Fatalf("can't parse policy file: %v", err)
|
|
}
|
|
lg = policy.Logger
|
|
lg.DebugContext(ctx, "swapped to new logger")
|
|
slog.SetDefault(lg)
|
|
|
|
if *metricsBind != "" || policy.Metrics != nil {
|
|
wg.Add(1)
|
|
|
|
ms := &metrics.Server{
|
|
Config: policy.Metrics,
|
|
Log: lg,
|
|
}
|
|
|
|
if policy.Metrics == nil {
|
|
lg.DebugContext(ctx, "migrating flags to metrics config", "bind", *metricsBind, "network", *metricsBindNetwork, "socket-mode", *socketMode)
|
|
ms.Config = &config.Metrics{
|
|
Bind: *metricsBind,
|
|
Network: *metricsBindNetwork,
|
|
SocketMode: *socketMode,
|
|
}
|
|
}
|
|
|
|
go ms.Run(ctx, wg.Done)
|
|
}
|
|
|
|
// Warn if persistent storage is used without a configured signing key
|
|
if policy.Store.IsPersistent() {
|
|
if *hs512Secret == "" && *ed25519PrivateKeyHex == "" && *ed25519PrivateKeyHexFile == "" {
|
|
lg.WarnContext(ctx, "[misconfiguration] persistent storage backend is configured, but no private key is set. "+
|
|
"Challenges will be invalidated when Anubis restarts. "+
|
|
"Set HS512_SECRET, ED25519_PRIVATE_KEY_HEX, or ED25519_PRIVATE_KEY_HEX_FILE to ensure challenges survive service restarts. "+
|
|
"See: https://anubis.techaro.lol/docs/admin/installation#key-generation")
|
|
}
|
|
}
|
|
|
|
ruleErrorIDs := make(map[string]string)
|
|
for _, rule := range policy.Bots {
|
|
if rule.Action != config.RuleDeny {
|
|
continue
|
|
}
|
|
|
|
hash := rule.Hash()
|
|
ruleErrorIDs[rule.Name] = hash
|
|
}
|
|
|
|
// replace the bot policy rules with a single rule that always benchmarks
|
|
if *debugBenchmarkJS {
|
|
policy.Bots = []botPolicy.Bot{{
|
|
Name: "",
|
|
Rules: botPolicy.NewHeaderExistsChecker("User-Agent"),
|
|
Action: config.RuleBenchmark,
|
|
}}
|
|
}
|
|
if *basePrefix != "" && !strings.HasPrefix(*basePrefix, "/") {
|
|
log.Fatalf("[misconfiguration] base-prefix must start with a slash, eg: /%s", *basePrefix)
|
|
} else if strings.HasSuffix(*basePrefix, "/") {
|
|
log.Fatalf("[misconfiguration] base-prefix must not end with a slash")
|
|
}
|
|
if *stripBasePrefix && *basePrefix == "" {
|
|
log.Fatalf("[misconfiguration] strip-base-prefix is set to true, but base-prefix is not set, " +
|
|
"this may result in unexpected behavior")
|
|
}
|
|
|
|
var ed25519Priv ed25519.PrivateKey
|
|
if *hs512Secret != "" && (*ed25519PrivateKeyHex != "" || *ed25519PrivateKeyHexFile != "") {
|
|
log.Fatal("do not specify both HS512 and ED25519 secrets")
|
|
} else if *hs512Secret != "" {
|
|
ed25519Priv = ed25519.PrivateKey(*hs512Secret)
|
|
} else if *ed25519PrivateKeyHex != "" && *ed25519PrivateKeyHexFile != "" {
|
|
log.Fatal("do not specify both ED25519_PRIVATE_KEY_HEX and ED25519_PRIVATE_KEY_HEX_FILE")
|
|
} else if *ed25519PrivateKeyHex != "" {
|
|
ed25519Priv, err = keyFromHex(*ed25519PrivateKeyHex)
|
|
if err != nil {
|
|
log.Fatalf("failed to parse and validate ED25519_PRIVATE_KEY_HEX: %v", err)
|
|
}
|
|
} else if *ed25519PrivateKeyHexFile != "" {
|
|
hexFile, err := os.ReadFile(*ed25519PrivateKeyHexFile)
|
|
if err != nil {
|
|
log.Fatalf("failed to read ED25519_PRIVATE_KEY_HEX_FILE %s: %v", *ed25519PrivateKeyHexFile, err)
|
|
}
|
|
|
|
ed25519Priv, err = keyFromHex(string(bytes.TrimSpace(hexFile)))
|
|
if err != nil {
|
|
log.Fatalf("failed to parse and validate content of ED25519_PRIVATE_KEY_HEX_FILE: %v", err)
|
|
}
|
|
} else {
|
|
_, ed25519Priv, err = ed25519.GenerateKey(rand.Reader)
|
|
if err != nil {
|
|
log.Fatalf("failed to generate ed25519 key: %v", err)
|
|
}
|
|
|
|
lg.WarnContext(ctx, "generating random key, Anubis will have strange behavior when multiple instances are behind the same load balancer target, for more information: see https://anubis.techaro.lol/docs/admin/installation#key-generation")
|
|
}
|
|
|
|
var redirectDomainsList []string
|
|
if *redirectDomains != "" {
|
|
domains := strings.SplitSeq(*redirectDomains, ",")
|
|
for domain := range domains {
|
|
_, err = url.Parse(domain)
|
|
if err != nil {
|
|
log.Fatalf("cannot parse redirect-domain %q: %s", domain, err.Error())
|
|
}
|
|
redirectDomainsList = append(redirectDomainsList, strings.TrimSpace(domain))
|
|
}
|
|
} else {
|
|
lg.WarnContext(ctx, "REDIRECT_DOMAINS is not set, Anubis will redirect to any domain, see https://anubis.techaro.lol/docs/admin/configuration/redirect-domains")
|
|
}
|
|
|
|
anubis.CookieName = *cookiePrefix + "-auth"
|
|
anubis.TestCookieName = *cookiePrefix + "-cookie-verification"
|
|
anubis.OriginalRefererCookieName = *cookiePrefix + "-original-referer"
|
|
anubis.ForcedLanguage = *forcedLanguage
|
|
|
|
if *useSimplifiedExplanation {
|
|
lg.WarnContext(ctx, "USE_SIMPLIFIED_EXPLANATION is deprecated and has no effect, the simplified explanation is always used")
|
|
}
|
|
|
|
// If OpenGraph configuration values are not set in the config file, use the
|
|
// values from flags / envvars.
|
|
if !policy.OpenGraph.Enabled {
|
|
policy.OpenGraph.Enabled = *ogPassthrough
|
|
policy.OpenGraph.ConsiderHost = *ogCacheConsiderHost
|
|
policy.OpenGraph.TimeToLive = *ogTimeToLive
|
|
policy.OpenGraph.Override = map[string]string{}
|
|
}
|
|
|
|
s, err := libanubis.New(libanubis.Options{
|
|
BasePrefix: *basePrefix,
|
|
StripBasePrefix: *stripBasePrefix,
|
|
Next: rp,
|
|
Policy: policy,
|
|
TargetHost: *targetHost,
|
|
TargetSNI: *targetSNI,
|
|
TargetInsecureSkipVerify: *targetInsecureSkipVerify,
|
|
ServeRobotsTXT: *robotsTxt,
|
|
ED25519PrivateKey: ed25519Priv,
|
|
HS512Secret: []byte(*hs512Secret),
|
|
CookieDomain: *cookieDomain,
|
|
CookieDynamicDomain: *cookieDynamicDomain,
|
|
CookieExpiration: *cookieExpiration,
|
|
CookiePartitioned: *cookiePartitioned,
|
|
DynamicCookieSuffix: *dynamicCookieSuffix,
|
|
RedirectDomains: redirectDomainsList,
|
|
Target: *target,
|
|
WebmasterEmail: *webmasterEmail,
|
|
OpenGraph: policy.OpenGraph,
|
|
CookieSecure: *cookieSecure,
|
|
CookieHttpOnly: *cookieHttpOnly,
|
|
CookieSameSite: parseSameSite(*cookieSameSite),
|
|
PublicUrl: *publicUrl,
|
|
JWTRestrictionHeader: *jwtRestrictionHeader,
|
|
Logger: policy.Logger.With("subsystem", "anubis"),
|
|
DifficultyInJWT: *difficultyInJWT,
|
|
PreserveRefererQueryParam: *preserveRefererQueryParam,
|
|
})
|
|
if err != nil {
|
|
log.Fatalf("can't construct libanubis.Server: %v", err)
|
|
}
|
|
|
|
var h http.Handler
|
|
h = s
|
|
h = internal.CustomRealIPHeader(*customRealIPHeader, h)
|
|
h = internal.RemoteXRealIP(*useRemoteAddress, *bindNetwork, h)
|
|
h = internal.XForwardedForToXRealIP(h)
|
|
h = internal.XForwardedForUpdate(*xffStripPrivate, h)
|
|
if policy.NeedJA4H {
|
|
h = internal.JA4H(h)
|
|
}
|
|
|
|
srv := internal.NewHTTPServer(h)
|
|
listener, listenerUrl, err := internal.SetupListener(*bindNetwork, *bind, *socketMode)
|
|
if err != nil {
|
|
log.Fatalf("SetupListener(%q, %q, %q): %v", *bindNetwork, *bind, *socketMode, err)
|
|
}
|
|
|
|
lg.InfoContext(ctx,
|
|
"listening",
|
|
"url", listenerUrl,
|
|
"difficulty", *challengeDifficulty,
|
|
"serveRobotsTXT", *robotsTxt,
|
|
"target", *target,
|
|
"version", anubis.Version,
|
|
"use-remote-address", *useRemoteAddress,
|
|
"custom-real-ip-header", *customRealIPHeader,
|
|
"debug-benchmark-js", *debugBenchmarkJS,
|
|
"og-passthrough", *ogPassthrough,
|
|
"og-expiry-time", *ogTimeToLive,
|
|
"base-prefix", *basePrefix,
|
|
"cookie-expiration-time", *cookieExpiration,
|
|
"rule-error-ids", ruleErrorIDs,
|
|
"public-url", *publicUrl,
|
|
)
|
|
|
|
go func() {
|
|
<-ctx.Done()
|
|
c, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
if err := srv.Shutdown(c); err != nil {
|
|
log.Printf("cannot shut down: %v", err)
|
|
}
|
|
}()
|
|
|
|
internal.SetHealth("anubis", healthv1.HealthCheckResponse_SERVING)
|
|
|
|
if err := srv.Serve(listener); !errors.Is(err, http.ErrServerClosed) {
|
|
log.Fatal(err)
|
|
}
|
|
wg.Wait()
|
|
}
|
|
|
|
func extractEmbedFS(fsys embed.FS, root string, destDir string) error {
|
|
if err := os.MkdirAll(destDir, 0755); err != nil {
|
|
return err
|
|
}
|
|
|
|
return fs.WalkDir(fsys, root, func(path string, d fs.DirEntry, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
relPath, err := filepath.Rel(root, path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
destPath := filepath.Join(destDir, root, relPath)
|
|
|
|
if d.IsDir() {
|
|
return os.MkdirAll(destPath, 0o700)
|
|
}
|
|
|
|
embeddedData, err := fs.ReadFile(fsys, path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return os.WriteFile(destPath, embeddedData, 0o644)
|
|
})
|
|
}
|