Update to Anubis v1.28.2 (#1)
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>
This commit was merged in pull request #1.
This commit is contained in:
1 parent
eb3e46d8d0
commit
caf4d72880
529 files changed
+33015
-6659
No files matched your search
@@ -0,0 +1,111 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// ErrBootstrapFailed is returned when the config directory cannot be prepared.
|
||||
var ErrBootstrapFailed = errors.New("anubis: config bootstrap failed")
|
||||
|
||||
// dataDirPlaceholder is the magic string the shipped config templates carry
|
||||
// wherever the live configuration directory belongs.
|
||||
//
|
||||
// Why isn't this hardcoded to C:\ProgramData?
|
||||
//
|
||||
// Excellent question, it mostly boils down to "we can't have nice things".
|
||||
// Normally the Program Data folder is in C:\ProgramData, but administrators
|
||||
// often decide to relocate it, and if the templates say it's C:\ProgramData
|
||||
// on a machine where it is in D: or whatever, the service tries to load
|
||||
// data from a folder that does not exist.
|
||||
//
|
||||
// Needless to say this is sub-optimal, so we have to do ugly hacks to work
|
||||
// around this. Any time the magic string is present in the upstream templates,
|
||||
// replace it with the actual location of the Anubis data directory.
|
||||
//
|
||||
// In an ideal world this would be %ANUBIS_DATA_DIR% but YAML fights us here
|
||||
// and I honestly don't care enough to work around it. Whatever. This is fine.
|
||||
const dataDirPlaceholder = "__ANUBIS_DATA_DIR__"
|
||||
|
||||
// bootstrapConfig describes the configuration directory from the templates
|
||||
// the .msi installer laid down next to the binary in Program Files.
|
||||
type bootstrapConfig struct {
|
||||
// SrcDir holds the read-only templates, such as the installer's etc folder.
|
||||
SrcDir string
|
||||
// DestDir is the live config directory. It and any missing parent are
|
||||
// created.
|
||||
DestDir string
|
||||
// Files are the base names to copy from SrcDir into DestDir.
|
||||
Files []string
|
||||
// DataDir is substituted for dataDirPlaceholder in each copied template.
|
||||
// Empty means no substitution.
|
||||
DataDir string
|
||||
}
|
||||
|
||||
// runBootstrap hydrates configuration from the installer's templates.
|
||||
//
|
||||
// The directory keeps whatever permissions it inherits from %ProgramData%,
|
||||
// which on a stock install means administrators and SYSTEM get full control
|
||||
// and local users get read access. Anubis does not narrow that, so treat
|
||||
// anubis.env as readable by anyone with a local account: on a multi-user
|
||||
// machine, supply the signing key through the environment rather than the
|
||||
// file.
|
||||
//
|
||||
// A file that already exists is never overwritten because it holds whatever
|
||||
// the administrator configured. It would be a bad user experience to nuke
|
||||
// configuration on upgrades.
|
||||
func runBootstrap(cfg bootstrapConfig) error {
|
||||
if err := os.MkdirAll(cfg.DestDir, 0o755); err != nil {
|
||||
return fmt.Errorf("%w: cannot create %s: %w", ErrBootstrapFailed, cfg.DestDir, err)
|
||||
}
|
||||
|
||||
for _, name := range cfg.Files {
|
||||
src := filepath.Join(cfg.SrcDir, name)
|
||||
dest := filepath.Join(cfg.DestDir, name)
|
||||
|
||||
if err := copyTemplate(src, dest, cfg.DataDir); err != nil {
|
||||
return fmt.Errorf("%w: %w", ErrBootstrapFailed, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// copyTemplate copies src to dest, substituting dataDir for every
|
||||
// dataDirPlaceholder on the way through. A dest that already exists is left
|
||||
// exactly as it is.
|
||||
func copyTemplate(src, dest, dataDir string) error {
|
||||
// Read the template first. Creating the destination and then failing to
|
||||
// find the source would leave an empty file behind, and because this
|
||||
// function never overwrites, that empty file would be permanent.
|
||||
body, err := os.ReadFile(src)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot read template %s: %w", src, err)
|
||||
}
|
||||
|
||||
if dataDir != "" {
|
||||
body = bytes.ReplaceAll(body, []byte(dataDirPlaceholder), []byte(dataDir))
|
||||
}
|
||||
|
||||
out, err := os.OpenFile(dest, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o640)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrExist) {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("cannot create %s: %w", dest, err)
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
if _, err := out.Write(body); err != nil {
|
||||
return fmt.Errorf("cannot write %s: %w", dest, err)
|
||||
}
|
||||
|
||||
if err := out.Close(); err != nil {
|
||||
return fmt.Errorf("cannot close %s: %w", dest, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+162
-199
@@ -21,7 +21,6 @@ import (
|
||||
"os"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"syscall"
|
||||
@@ -32,12 +31,12 @@ import (
|
||||
"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/lib/thoth"
|
||||
"github.com/TecharoHQ/anubis/web"
|
||||
"github.com/facebookgo/flagenv"
|
||||
"github.com/google/uuid"
|
||||
_ "github.com/joho/godotenv/autoload"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
healthv1 "google.golang.org/grpc/health/grpc_health_v1"
|
||||
)
|
||||
|
||||
@@ -50,12 +49,14 @@ var (
|
||||
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", false, "if true, sets the partitioned flag on Anubis cookies, enabling CHIPS support")
|
||||
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", false, "if true, replaces the text when clicking \"Why am I seeing this?\" with a more simplified text for a non-tech-savvy audience.")
|
||||
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")
|
||||
@@ -85,10 +86,12 @@ var (
|
||||
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, "if set, connect to Thoth over plain HTTP/2, don't enable this unless support told you to")
|
||||
thothURL = flag.String("thoth-url", "", "if set, URL for Thoth, the IP reputation database for Anubis")
|
||||
thothToken = flag.String("thoth-token", "", "if set, API token for Thoth, the IP reputation database for Anubis")
|
||||
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) {
|
||||
@@ -109,7 +112,7 @@ func doHealthCheck() error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to fetch metrics: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer resp.Body.Close() //nolint:errcheck
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("unexpected status code: %d", resp.StatusCode)
|
||||
@@ -118,33 +121,6 @@ func doHealthCheck() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseBindNetFromAddr determine bind network and address based on the given network and address.
|
||||
func parseBindNetFromAddr(address string) (string, string) {
|
||||
defaultScheme := "http://"
|
||||
if !strings.Contains(address, "://") {
|
||||
if strings.HasPrefix(address, ":") {
|
||||
address = defaultScheme + "localhost" + address
|
||||
} else {
|
||||
address = defaultScheme + address
|
||||
}
|
||||
}
|
||||
|
||||
bindUri, err := url.Parse(address)
|
||||
if err != nil {
|
||||
log.Fatal(fmt.Errorf("failed to parse bind URL: %w", err))
|
||||
}
|
||||
|
||||
switch bindUri.Scheme {
|
||||
case "unix":
|
||||
return "unix", bindUri.Path
|
||||
case "tcp", "http", "https":
|
||||
return "tcp", bindUri.Host
|
||||
default:
|
||||
log.Fatal(fmt.Errorf("unsupported network scheme %s in address %s", bindUri.Scheme, address))
|
||||
}
|
||||
return "", address
|
||||
}
|
||||
|
||||
func parseSameSite(s string) http.SameSite {
|
||||
switch strings.ToLower(s) {
|
||||
case "none":
|
||||
@@ -161,53 +137,6 @@ func parseSameSite(s string) http.SameSite {
|
||||
return http.SameSiteDefaultMode
|
||||
}
|
||||
|
||||
func setupListener(network string, address string) (net.Listener, string) {
|
||||
formattedAddress := ""
|
||||
|
||||
if network == "" {
|
||||
// keep compatibility
|
||||
network, address = parseBindNetFromAddr(address)
|
||||
}
|
||||
|
||||
switch network {
|
||||
case "unix":
|
||||
formattedAddress = "unix:" + address
|
||||
case "tcp":
|
||||
if strings.HasPrefix(address, ":") { // assume it's just a port e.g. :4259
|
||||
formattedAddress = "http://localhost" + address
|
||||
} else {
|
||||
formattedAddress = "http://" + address
|
||||
}
|
||||
default:
|
||||
formattedAddress = fmt.Sprintf(`(%s) %s`, network, address)
|
||||
}
|
||||
|
||||
listener, err := net.Listen(network, address)
|
||||
if err != nil {
|
||||
log.Fatal(fmt.Errorf("failed to bind to %s: %w", formattedAddress, err))
|
||||
}
|
||||
|
||||
// additional permission handling for unix sockets
|
||||
if network == "unix" {
|
||||
mode, err := strconv.ParseUint(*socketMode, 8, 0)
|
||||
if err != nil {
|
||||
listener.Close()
|
||||
log.Fatal(fmt.Errorf("could not parse socket mode %s: %w", *socketMode, err))
|
||||
}
|
||||
|
||||
err = os.Chmod(address, os.FileMode(mode))
|
||||
if err != nil {
|
||||
err := listener.Close()
|
||||
if err != nil {
|
||||
log.Printf("failed to close listener: %v", err)
|
||||
}
|
||||
log.Fatal(fmt.Errorf("could not change socket mode: %w", err))
|
||||
}
|
||||
}
|
||||
|
||||
return listener, formattedAddress
|
||||
}
|
||||
|
||||
func makeReverseProxy(target string, targetSNI string, targetHost string, insecureSkipVerify bool, targetDisableKeepAlive bool) (http.Handler, error) {
|
||||
targetUri, err := url.Parse(target)
|
||||
if err != nil {
|
||||
@@ -245,38 +174,79 @@ func makeReverseProxy(target string, targetSNI string, targetHost string, insecu
|
||||
transport.TLSClientConfig.ServerName = targetSNI
|
||||
}
|
||||
|
||||
rp := httputil.NewSingleHostReverseProxy(targetUri)
|
||||
rp.Transport = transport
|
||||
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 != "" || targetSNI == "auto" {
|
||||
originalDirector := rp.Director
|
||||
rp.Director = func(req *http.Request) {
|
||||
originalDirector(req)
|
||||
if targetHost != "" {
|
||||
req.Host = targetHost
|
||||
r.Out.Host = targetHost
|
||||
}
|
||||
if targetSNI == "auto" {
|
||||
transport.TLSClientConfig.ServerName = req.Host
|
||||
}
|
||||
}
|
||||
|
||||
},
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
internal.SetHealth("anubis", healthv1.HealthCheckResponse_NOT_SERVING)
|
||||
|
||||
lg := internal.InitSlog(*slogLevel, os.Stderr)
|
||||
lg.Info("starting up Anubis")
|
||||
if handleBootstrapFlag() {
|
||||
return
|
||||
}
|
||||
|
||||
if *healthcheck {
|
||||
log.Println("running healthcheck")
|
||||
@@ -287,7 +257,7 @@ func main() {
|
||||
}
|
||||
|
||||
if *extractResources != "" {
|
||||
if err := extractEmbedFS(data.BotPolicies, ".", *extractResources); err != nil {
|
||||
if err := extractEmbedFS(data.BotPolicies, ".", filepath.Join(*extractResources, "data")); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := extractEmbedFS(web.Static, "static", *extractResources); err != nil {
|
||||
@@ -297,16 +267,25 @@ func main() {
|
||||
return
|
||||
}
|
||||
|
||||
if runPlatformService(run) {
|
||||
return
|
||||
}
|
||||
|
||||
// install signal handler
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
wg := new(sync.WaitGroup)
|
||||
run(ctx)
|
||||
}
|
||||
|
||||
if *metricsBind != "" {
|
||||
wg.Add(1)
|
||||
go metricsServer(ctx, *lg.With("subsystem", "metrics"), wg.Done)
|
||||
}
|
||||
// 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
|
||||
@@ -322,37 +301,45 @@ func main() {
|
||||
log.Fatalf("you can't set COOKIE_DOMAIN and COOKIE_DYNAMIC_DOMAIN at the same time")
|
||||
}
|
||||
|
||||
// Thoth configuration
|
||||
switch {
|
||||
case *thothURL != "" && *thothToken == "":
|
||||
lg.Warn("THOTH_URL is set but no THOTH_TOKEN is set")
|
||||
case *thothURL == "" && *thothToken != "":
|
||||
lg.Warn("THOTH_TOKEN is set but no THOTH_URL is set")
|
||||
case *thothURL != "" && *thothToken != "":
|
||||
lg.Debug("connecting to Thoth")
|
||||
thothClient, err := thoth.New(ctx, *thothURL, *thothToken, *thothInsecure)
|
||||
if err != nil {
|
||||
log.Fatalf("can't dial thoth at %s: %v", *thothURL, err)
|
||||
}
|
||||
|
||||
ctx = thoth.With(ctx, thothClient)
|
||||
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.Info("loading policy file", "fname", *policyFname)
|
||||
policy, err := libanubis.LoadPoliciesOrDefault(ctx, *policyFname, *challengeDifficulty, *slogLevel)
|
||||
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.Debug("swapped to new 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.Warn("[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. " +
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -413,13 +400,13 @@ func main() {
|
||||
log.Fatalf("failed to generate ed25519 key: %v", err)
|
||||
}
|
||||
|
||||
lg.Warn("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")
|
||||
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.Split(*redirectDomains, ",")
|
||||
for _, domain := range domains {
|
||||
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())
|
||||
@@ -427,13 +414,17 @@ func main() {
|
||||
redirectDomainsList = append(redirectDomainsList, strings.TrimSpace(domain))
|
||||
}
|
||||
} else {
|
||||
lg.Warn("REDIRECT_DOMAINS is not set, Anubis will only redirect to the same domain a request is coming from, see https://anubis.techaro.lol/docs/admin/configuration/redirect-domains")
|
||||
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
|
||||
anubis.UseSimplifiedExplanation = *useSimplifiedExplanation
|
||||
|
||||
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.
|
||||
@@ -445,30 +436,33 @@ func main() {
|
||||
}
|
||||
|
||||
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,
|
||||
RedirectDomains: redirectDomainsList,
|
||||
Target: *target,
|
||||
WebmasterEmail: *webmasterEmail,
|
||||
OpenGraph: policy.OpenGraph,
|
||||
CookieSecure: *cookieSecure,
|
||||
CookieSameSite: parseSameSite(*cookieSameSite),
|
||||
PublicUrl: *publicUrl,
|
||||
JWTRestrictionHeader: *jwtRestrictionHeader,
|
||||
Logger: policy.Logger.With("subsystem", "anubis"),
|
||||
DifficultyInJWT: *difficultyInJWT,
|
||||
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)
|
||||
@@ -480,11 +474,17 @@ func main() {
|
||||
h = internal.RemoteXRealIP(*useRemoteAddress, *bindNetwork, h)
|
||||
h = internal.XForwardedForToXRealIP(h)
|
||||
h = internal.XForwardedForUpdate(*xffStripPrivate, h)
|
||||
h = internal.JA4H(h)
|
||||
if policy.NeedJA4H {
|
||||
h = internal.JA4H(h)
|
||||
}
|
||||
|
||||
srv := http.Server{Handler: h, ErrorLog: internal.GetFilteredHTTPLogger()}
|
||||
listener, listenerUrl := setupListener(*bindNetwork, *bind)
|
||||
lg.Info(
|
||||
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,
|
||||
@@ -492,6 +492,7 @@ func main() {
|
||||
"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,
|
||||
@@ -518,49 +519,11 @@ func main() {
|
||||
wg.Wait()
|
||||
}
|
||||
|
||||
func metricsServer(ctx context.Context, lg slog.Logger, done func()) {
|
||||
defer done()
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/metrics", promhttp.Handler())
|
||||
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
|
||||
st, ok := internal.GetHealth("anubis")
|
||||
if !ok {
|
||||
slog.Error("health service anubis does not exist, file a bug")
|
||||
}
|
||||
|
||||
switch st {
|
||||
case healthv1.HealthCheckResponse_NOT_SERVING:
|
||||
http.Error(w, "NOT OK", http.StatusInternalServerError)
|
||||
return
|
||||
case healthv1.HealthCheckResponse_SERVING:
|
||||
fmt.Fprintln(w, "OK")
|
||||
return
|
||||
default:
|
||||
http.Error(w, "UNKNOWN", http.StatusFailedDependency)
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
srv := http.Server{Handler: mux, ErrorLog: internal.GetFilteredHTTPLogger()}
|
||||
listener, metricsUrl := setupListener(*metricsBindNetwork, *metricsBind)
|
||||
lg.Debug("listening for metrics", "url", metricsUrl)
|
||||
|
||||
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)
|
||||
}
|
||||
}()
|
||||
|
||||
if err := srv.Serve(listener); !errors.Is(err, http.ErrServerClosed) {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMakeReverseProxy(t *testing.T) {
|
||||
type received struct {
|
||||
host string
|
||||
path string
|
||||
query string
|
||||
hdr http.Header
|
||||
}
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
targetHost string
|
||||
reqHost string
|
||||
reqPath string
|
||||
reqHeaders map[string]string
|
||||
wantHost string // empty means "same as the target server's host"
|
||||
}{
|
||||
{
|
||||
name: "default preserves inbound host",
|
||||
reqHost: "anubis.example.com",
|
||||
reqPath: "/foo/bar?baz=qux",
|
||||
},
|
||||
{
|
||||
// gitweb uses ';' as a query separator (e.g.
|
||||
// /?p=repo.git;a=summary). httputil's Rewrite mode re-encodes the
|
||||
// query and would otherwise drop these parameters entirely.
|
||||
name: "semicolon-delimited query is preserved",
|
||||
reqHost: "anubis.example.com",
|
||||
reqPath: "/?p=testing.git;a=summary",
|
||||
},
|
||||
{
|
||||
name: "target host override",
|
||||
targetHost: "upstream.internal",
|
||||
reqHost: "anubis.example.com",
|
||||
reqPath: "/",
|
||||
wantHost: "upstream.internal",
|
||||
},
|
||||
{
|
||||
name: "forwarding headers are passed through",
|
||||
reqHost: "anubis.example.com",
|
||||
reqPath: "/",
|
||||
reqHeaders: map[string]string{
|
||||
"X-Forwarded-For": "203.0.113.7, 198.51.100.2",
|
||||
"X-Forwarded-Host": "anubis.example.com",
|
||||
"X-Forwarded-Proto": "https",
|
||||
"Forwarded": "for=203.0.113.7;proto=https",
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
gotCh := make(chan received, 1)
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
gotCh <- received{
|
||||
host: r.Host,
|
||||
path: r.URL.Path,
|
||||
query: r.URL.RawQuery,
|
||||
hdr: r.Header.Clone(),
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
t.Cleanup(target.Close)
|
||||
|
||||
h, err := makeReverseProxy(target.URL, "", tt.targetHost, false, false)
|
||||
if err != nil {
|
||||
t.Fatalf("makeReverseProxy: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "http://"+tt.reqHost+tt.reqPath, nil)
|
||||
req.Host = tt.reqHost
|
||||
for k, v := range tt.reqHeaders {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("unexpected status from proxy: got %d, want %d", rec.Code, http.StatusNoContent)
|
||||
}
|
||||
|
||||
got := <-gotCh
|
||||
|
||||
wantHost := tt.wantHost
|
||||
if wantHost == "" {
|
||||
wantHost = tt.reqHost
|
||||
}
|
||||
if got.host != wantHost {
|
||||
t.Errorf("upstream Host: got %q, want %q", got.host, wantHost)
|
||||
}
|
||||
|
||||
wantURL, _ := url.Parse("http://x" + tt.reqPath)
|
||||
if got.path != wantURL.Path {
|
||||
t.Errorf("upstream path: got %q, want %q", got.path, wantURL.Path)
|
||||
}
|
||||
if got.query != wantURL.RawQuery {
|
||||
t.Errorf("upstream query: got %q, want %q", got.query, wantURL.RawQuery)
|
||||
}
|
||||
|
||||
for k, want := range tt.reqHeaders {
|
||||
if gotVal := got.hdr.Get(k); gotVal != want {
|
||||
t.Errorf("upstream header %q: got %q, want %q", k, gotVal, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//go:build !windows
|
||||
|
||||
package main
|
||||
|
||||
import "context"
|
||||
|
||||
// Hooks for Windows service management. These are no-ops outside of a
|
||||
// Windows environment.
|
||||
|
||||
func platformStartup() {}
|
||||
func handleBootstrapFlag() bool { return false }
|
||||
func runPlatformService(fn func(context.Context)) bool { return false }
|
||||
@@ -0,0 +1,383 @@
|
||||
//go:build windows
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/TecharoHQ/anubis/internal"
|
||||
"github.com/TecharoHQ/anubis/internal/servicesid"
|
||||
"github.com/joho/godotenv"
|
||||
"golang.org/x/sys/windows"
|
||||
"golang.org/x/sys/windows/svc"
|
||||
healthv1 "google.golang.org/grpc/health/grpc_health_v1"
|
||||
)
|
||||
|
||||
// windowsBootstrapConfig is the Windows-only installer hook. If set, this
|
||||
// will trigger hydrating %ProgramData% from the etc folder the installer laid
|
||||
// down under %ProgramFiles%.
|
||||
var windowsBootstrapConfig = flag.Bool("windows-bootstrap-config", false, "if true, seed and harden the Windows config directory, then exit (used by the MSI installer)")
|
||||
|
||||
// programData is the directory Windows keeps machine-wide application state
|
||||
// in. It is C:\ProgramData on a stock install, but it is relocatable and
|
||||
// enterprise images do relocate it, so nothing here may assume the C: path.
|
||||
//
|
||||
// It is empty when Windows did not tell us where it is. Callers must check,
|
||||
// because filepath.Join would otherwise turn an unset ProgramData into the
|
||||
// relative path "Techaro\Anubis", writing the signing key somewhere
|
||||
// unpredictable and hardening a directory that is not the one in use.
|
||||
var programData = os.Getenv("ProgramData")
|
||||
|
||||
// dataDir is where the MSI installs the live configuration, the policy file
|
||||
// and the logs. It is empty exactly when programData is.
|
||||
var dataDir = func() string {
|
||||
if programData == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
return filepath.Join(programData, "Techaro", "Anubis")
|
||||
}()
|
||||
|
||||
// bootstrapFiles are copied out of the installer's etc folder on first install.
|
||||
var bootstrapFiles = []string{"anubis.env", "anubis.yaml"}
|
||||
|
||||
// bootstrapLogName is the file the installer's bootstrap run writes its
|
||||
// diagnostics to. See writeBootstrapLog for where it ends up.
|
||||
const bootstrapLogName = "anubis-bootstrap.log"
|
||||
|
||||
// platformStartup prepares a service process before flags are parsed.
|
||||
//
|
||||
// A Windows service starts with no usable stderr and with its working
|
||||
// directory set to the system folder, so the godotenv autoload import finds
|
||||
// nothing and anything written to stderr is discarded. Both are fixed here,
|
||||
// before any code can log or read a flag.
|
||||
func platformStartup() {
|
||||
isService, err := svc.IsWindowsService()
|
||||
if err != nil || !isService {
|
||||
return
|
||||
}
|
||||
|
||||
if dataDir == "" {
|
||||
// Nothing to redirect to and no config file to find. Anubis will come
|
||||
// up on defaults and fail somewhere more legible than here.
|
||||
return
|
||||
}
|
||||
|
||||
// XXX(Xe): overwrite os.Stderr with anubis-startup.log. This is done because
|
||||
// msiexec sucks. See the doc comment for handleBootstrapFlag.
|
||||
redirectStderr(filepath.Join(dataDir, "anubis-startup.log"))
|
||||
|
||||
// Load, not Overload: a real environment variable set on the service must
|
||||
// win over the file, matching how the Linux packages behave.
|
||||
if err := godotenv.Load(filepath.Join(dataDir, "anubis.env")); err != nil {
|
||||
log.Printf("cannot load %s: %v", filepath.Join(dataDir, "anubis.env"), err)
|
||||
}
|
||||
}
|
||||
|
||||
// redirectStderr points os.Stderr and the standard logger at path.
|
||||
//
|
||||
// Failures are silent because there is nowhere left to report them to.
|
||||
func redirectStderr(path string) {
|
||||
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o640)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
os.Stderr = f
|
||||
log.SetOutput(f)
|
||||
}
|
||||
|
||||
// handleBootstrapFlag runs the installation configuration bootstrap when
|
||||
// --windows-bootstrap-config is set.
|
||||
//
|
||||
// Due to facts and circumstances beyond my control, msiexec discards _all_
|
||||
// logging messages when it runs Anubis with the --windows-bootstrap-config
|
||||
// set during install. In order to have _some_ kind of debugging surface,
|
||||
// we have to write logs to %ProgramData%\Techaro\Anubis\anubis-bootstrap.log.
|
||||
//
|
||||
// Additionally, things here have to return successful error codes even when
|
||||
// operations fail because if this returns a non-success exit code then it
|
||||
// surfaces as the obscure msiexec "Error 1603" without any details.
|
||||
//
|
||||
// I really hate this, but I don't really see a better option here.
|
||||
func handleBootstrapFlag() bool {
|
||||
if !*windowsBootstrapConfig {
|
||||
return false
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
lg := log.New(io.MultiWriter(os.Stderr, &buf), "", log.LstdFlags|log.LUTC)
|
||||
|
||||
lg.Printf("bootstrapping the Anubis config directory")
|
||||
lg.Printf("ProgramData is %q, config directory is %q", programData, dataDir)
|
||||
|
||||
err := bootstrapConfigDir(lg)
|
||||
if err != nil {
|
||||
lg.Printf("bootstrap failed: %v", err)
|
||||
} else {
|
||||
lg.Printf("bootstrap finished")
|
||||
}
|
||||
|
||||
writeBootstrapLog(buf.Bytes())
|
||||
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// bootstrapConfigDir seeds the config directory from the installer's templates.
|
||||
func bootstrapConfigDir(lg *log.Logger) error {
|
||||
if dataDir == "" {
|
||||
return errors.New("ProgramData is not set, refusing to guess where the configuration directory is")
|
||||
}
|
||||
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot find my own path: %w", err)
|
||||
}
|
||||
|
||||
// The installer lays the binary down in <prefix>\bin and the templates in
|
||||
// <prefix>\etc.
|
||||
srcDir := filepath.Join(filepath.Dir(filepath.Dir(exe)), "etc")
|
||||
|
||||
lg.Printf("copying %v out of %q", bootstrapFiles, srcDir)
|
||||
|
||||
if err := runBootstrap(bootstrapConfig{
|
||||
SrcDir: srcDir,
|
||||
DestDir: dataDir,
|
||||
Files: bootstrapFiles,
|
||||
DataDir: dataDir,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
lg.Printf("granting %s (%s) access to %q", servicesid.AnubisServiceName, servicesid.AnubisServiceSID, dataDir)
|
||||
|
||||
return grantServiceAccess(dataDir)
|
||||
}
|
||||
|
||||
// writeBootstrapLog appends the bootstrap's diagnostics to the first place
|
||||
// it can be written to.
|
||||
//
|
||||
// Normally it writes to %ProgramData%\Techaro\Anubis\anubis-bootstrap.log,
|
||||
// but if it can't then it just makes a temporary folder in C:\Windows\Temp
|
||||
// and writes them there.
|
||||
//
|
||||
// Hopefully this fallback logic never runs, but sometimes you gotta have
|
||||
// a way to fall back.
|
||||
//
|
||||
// Failures in this process are silent because there is nowhere left to
|
||||
// report them to.
|
||||
func writeBootstrapLog(body []byte) {
|
||||
var paths []string
|
||||
if dataDir != "" {
|
||||
paths = append(paths, filepath.Join(dataDir, bootstrapLogName))
|
||||
}
|
||||
paths = append(paths, filepath.Join(os.TempDir(), bootstrapLogName))
|
||||
|
||||
for _, path := range paths {
|
||||
f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o640)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
_, writeErr := f.Write(body)
|
||||
closeErr := f.Close()
|
||||
|
||||
if writeErr == nil && closeErr == nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// grantServiceAccess gives the Anubis service read and write access to its own
|
||||
// data directory.
|
||||
//
|
||||
// The directory otherwise keeps whatever it inherits from %ProgramData%, which
|
||||
// grants SYSTEM and the administrators full control and says nothing at all
|
||||
// about NT SERVICE\Anubis. Without this the service cannot read anubis.env or
|
||||
// create anubis.log, so it dies on startup with a permission error.
|
||||
//
|
||||
// This deliberately does not shell out to icacls. icacls reverse-maps every SID
|
||||
// it is handed back to an account name, and LSA will not map an NT SERVICE SID
|
||||
// for a service that is not registered yet. The bootstrap runs before
|
||||
// InstallServices, so icacls fails the whole invocation with error 1332 and
|
||||
// applies none of it. The API below takes the SID as bytes and never asks LSA
|
||||
// anything, which is what lets the grant happen ahead of the service.
|
||||
//
|
||||
// The ACE is inheritable, and SetNamedSecurityInfo pushes inheritable ACEs down
|
||||
// to existing children, so files left behind by an older install pick it up too.
|
||||
func grantServiceAccess(dir string) error {
|
||||
sid, err := windows.StringToSid(servicesid.AnubisServiceSID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot parse the %s service SID %s: %w", servicesid.AnubisServiceName, servicesid.AnubisServiceSID, err)
|
||||
}
|
||||
|
||||
sd, err := windows.GetNamedSecurityInfo(dir, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot read the permissions of %s: %w", dir, err)
|
||||
}
|
||||
|
||||
dacl, _, err := sd.DACL()
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot read the permissions of %s: %w", dir, err)
|
||||
}
|
||||
|
||||
// Modify, which is what Windows calls this combination: enough to read the
|
||||
// config, write and rotate the logs, and delete the rotated ones. It leaves
|
||||
// out WRITE_DAC and WRITE_OWNER, so the service cannot widen its own grant.
|
||||
const modify = windows.FILE_GENERIC_READ |
|
||||
windows.FILE_GENERIC_WRITE |
|
||||
windows.FILE_GENERIC_EXECUTE |
|
||||
windows.DELETE
|
||||
|
||||
merged, err := windows.ACLFromEntries([]windows.EXPLICIT_ACCESS{{
|
||||
AccessPermissions: modify,
|
||||
AccessMode: windows.GRANT_ACCESS,
|
||||
Inheritance: windows.SUB_CONTAINERS_AND_OBJECTS_INHERIT,
|
||||
Trustee: windows.TRUSTEE{
|
||||
TrusteeForm: windows.TRUSTEE_IS_SID,
|
||||
TrusteeType: windows.TRUSTEE_IS_USER,
|
||||
TrusteeValue: windows.TrusteeValueFromSID(sid),
|
||||
},
|
||||
}}, dacl)
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot add %s to the permissions of %s: %w", servicesid.AnubisServiceSID, dir, err)
|
||||
}
|
||||
|
||||
if err := windows.SetNamedSecurityInfo(dir, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION, nil, nil, merged, nil); err != nil {
|
||||
return fmt.Errorf("cannot write the permissions of %s: %w", dir, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// runPlatformService runs fn under the service control manager when this
|
||||
// process was started as a Windows service. It reports whether it did so.
|
||||
func runPlatformService(fn func(context.Context)) bool {
|
||||
isService, err := svc.IsWindowsService()
|
||||
if err != nil || !isService {
|
||||
return false
|
||||
}
|
||||
|
||||
if err := svc.Run("Anubis", &anubisService{fn: fn}); err != nil {
|
||||
log.Fatalf("service failed: %v", err)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// anubisService adapts run to the service control manager's interface.
|
||||
type anubisService struct {
|
||||
fn func(context.Context)
|
||||
}
|
||||
|
||||
// startPollInterval is how often Execute asks whether Anubis is serving yet.
|
||||
const startPollInterval = 100 * time.Millisecond
|
||||
|
||||
// startWaitHint is how long the service control manager is told to expect
|
||||
// between two checkpoints while the service is starting.
|
||||
const startWaitHint = 30 * time.Second
|
||||
|
||||
// Execute implements svc.Handler. It starts Anubis in the background, waits
|
||||
// for it to actually be serving before reporting the service as running, and
|
||||
// translates a stop or shutdown request into cancellation of its context.
|
||||
func (s *anubisService) Execute(args []string, r <-chan svc.ChangeRequest, changes chan<- svc.Status) (bool, uint32) {
|
||||
const accepted = svc.AcceptStop | svc.AcceptShutdown
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
s.fn(ctx)
|
||||
}()
|
||||
|
||||
if !waitUntilServing(r, changes, done) {
|
||||
// Anubis gave up before it ever served a request. Returning a
|
||||
// service-specific error makes "sc start anubis" fail and puts a 7024
|
||||
// in the event log, rather than the service reporting a clean start
|
||||
// and then disappearing for reasons nobody wrote down.
|
||||
//
|
||||
// svc.Run reports the final Stopped status itself, using exactly
|
||||
// these two return values, so sending one here would only report a
|
||||
// clean stop a moment before the real one.
|
||||
cancel()
|
||||
<-done
|
||||
|
||||
return true, 1
|
||||
}
|
||||
|
||||
changes <- svc.Status{State: svc.Running, Accepts: accepted}
|
||||
|
||||
for {
|
||||
select {
|
||||
case c := <-r:
|
||||
switch c.Cmd {
|
||||
case svc.Interrogate:
|
||||
changes <- c.CurrentStatus
|
||||
case svc.Stop, svc.Shutdown:
|
||||
changes <- svc.Status{State: svc.StopPending}
|
||||
cancel()
|
||||
<-done
|
||||
return false, 0
|
||||
}
|
||||
case <-done:
|
||||
// Anubis stopped on its own, which the control manager treats as
|
||||
// the service exiting.
|
||||
return false, 0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// waitUntilServing blocks until Anubis is listening and known healthy.
|
||||
//
|
||||
// Nearly everything that can go wrong with starting Anubis will happen
|
||||
// while the service is managed by the Windows service manager. Windows'
|
||||
// service management subsystem will wait for the service to be marked
|
||||
// as running before `sc start Anubis` or `Start-Service Anubis` return.
|
||||
//
|
||||
// This interrogates Anubis' health every 100ms until it starts
|
||||
// successfully. In most cases this will iterate once.
|
||||
func waitUntilServing(r <-chan svc.ChangeRequest, changes chan<- svc.Status, done <-chan struct{}) bool {
|
||||
status := svc.Status{
|
||||
State: svc.StartPending,
|
||||
WaitHint: uint32(startWaitHint / time.Millisecond),
|
||||
}
|
||||
changes <- status
|
||||
|
||||
tick := time.NewTicker(startPollInterval)
|
||||
defer tick.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case c := <-r:
|
||||
// Stop is not in Accepts yet, so an interrogation is the only
|
||||
// thing that should arrive here.
|
||||
if c.Cmd == svc.Interrogate {
|
||||
changes <- status
|
||||
}
|
||||
case <-done:
|
||||
return false
|
||||
case <-tick.C:
|
||||
if st, ok := internal.GetHealth("anubis"); ok && st == healthv1.HealthCheckResponse_SERVING {
|
||||
return true
|
||||
}
|
||||
|
||||
status.CheckPoint++
|
||||
changes <- status
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAutomaticSNI(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
seen := map[string]string{}
|
||||
target := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock(); seen[r.Host] = r.TLS.ServerName; mu.Unlock() }))
|
||||
target.TLS = &tls.Config{}
|
||||
target.StartTLS()
|
||||
defer target.Close()
|
||||
proxy, err := makeReverseProxy(target.URL, "auto", "", true, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for _, host := range []string{"first.example", "second.example", "third.example:443"} {
|
||||
wg.Go(func() {
|
||||
r := httptest.NewRequest("GET", "https://"+host+"/", nil)
|
||||
proxy.ServeHTTP(httptest.NewRecorder(), r)
|
||||
})
|
||||
}
|
||||
wg.Wait()
|
||||
for host, sni := range seen {
|
||||
if sni != strings.Split(host, ":")[0] {
|
||||
t.Errorf("host %s used SNI %s", host, sni)
|
||||
}
|
||||
}
|
||||
if len(seen) != 3 {
|
||||
t.Fatalf("got %d requests", len(seen))
|
||||
}
|
||||
}
|
||||
+19
-11
@@ -19,6 +19,7 @@ var (
|
||||
dockerLabels = flag.String("docker-labels", os.Getenv("DOCKER_METADATA_OUTPUT_LABELS"), "Docker image labels")
|
||||
dockerRepo = flag.String("docker-repo", "registry.int.xeserv.us/techaro/anubis", "Docker image repository for Anubis")
|
||||
dockerTags = flag.String("docker-tags", os.Getenv("DOCKER_METADATA_OUTPUT_TAGS"), "newline separated docker tags including the registry name")
|
||||
dryRun = flag.Bool("dry-run", false, "If set, don't actually run builds")
|
||||
githubEventName = flag.String("github-event-name", "", "GitHub event name")
|
||||
pullRequestID = flag.Int("pull-request-id", -1, "GitHub pull request ID")
|
||||
slogLevel = flag.String("slog-level", "INFO", "logging level (see https://pkg.go.dev/log/slog#hdr-Levels)")
|
||||
@@ -102,14 +103,21 @@ func main() {
|
||||
tags = append(tags, img.tag)
|
||||
}
|
||||
|
||||
output, err := run(fmt.Sprintf("ko build --platform=all --base-import-paths --tags=%q --image-user=1000 --image-annotation=%q --image-label=%q ./cmd/anubis | tail -n1", strings.Join(tags, ","), *dockerAnnotations, *dockerLabels))
|
||||
if err != nil {
|
||||
log.Fatalf("can't run ko build, check stderr: %v", err)
|
||||
cmd := fmt.Sprintf("ko build --platform=all --base-import-paths --tags=%q --image-user=1000 --image-annotation=%q --image-label=%q ./cmd/anubis | tail -n1", strings.Join(tags, ","), *dockerAnnotations, *dockerLabels)
|
||||
|
||||
switch *dryRun {
|
||||
case true:
|
||||
fmt.Println("[would run]", cmd)
|
||||
case false:
|
||||
output, err := run(cmd)
|
||||
if err != nil {
|
||||
log.Fatalf("can't run ko build, check stderr: %v", err)
|
||||
}
|
||||
|
||||
sp := strings.SplitN(output, "@", 2)
|
||||
|
||||
setOutput("digest", sp[1])
|
||||
}
|
||||
|
||||
sp := strings.SplitN(output, "@", 2)
|
||||
|
||||
setOutput("digest", sp[1])
|
||||
}
|
||||
|
||||
type image struct {
|
||||
@@ -159,8 +167,8 @@ func run(command string) (string, error) {
|
||||
}
|
||||
|
||||
func setOutput(key, val string) {
|
||||
github_output := os.Getenv("GITHUB_OUTPUT")
|
||||
f, _ := os.OpenFile(github_output, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
|
||||
fmt.Fprintf(f, "%s=%s\n", key, val)
|
||||
f.Close()
|
||||
github_output := os.Getenv("GITHUB_OUTPUT")
|
||||
f, _ := os.OpenFile(github_output, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644) //nolint:all
|
||||
fmt.Fprintf(f, "%s=%s\n", key, val) //nolint:all
|
||||
f.Close() //nolint:all
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/TecharoHQ/anubis/lib/config"
|
||||
@@ -78,14 +79,18 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatalf("failed to fetch robots.txt from URL: %v", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
defer resp.Body.Close() //nolint:errcheck
|
||||
input = resp.Body
|
||||
} else {
|
||||
file, err := os.Open(*inputFile)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to open input file: %v", err)
|
||||
}
|
||||
defer file.Close()
|
||||
defer func() {
|
||||
if err := file.Close(); err != nil {
|
||||
log.Fatalf("can't close output file %s: %v", file.Name(), err)
|
||||
}
|
||||
}()
|
||||
input = file
|
||||
}
|
||||
|
||||
@@ -210,11 +215,8 @@ func parseRobotsTxt(input io.Reader) ([]RobotsRule, error) {
|
||||
|
||||
// Mark blacklisted user agents (those with "Disallow: /")
|
||||
for i := range rules {
|
||||
for _, disallow := range rules[i].Disallows {
|
||||
if disallow == "/" {
|
||||
rules[i].IsBlacklist = true
|
||||
break
|
||||
}
|
||||
if slices.Contains(rules[i].Disallows, "/") {
|
||||
rules[i].IsBlacklist = true
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -96,7 +96,11 @@ func TestDataFileConversion(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to open robots file %s: %v", robotsPath, err)
|
||||
}
|
||||
defer robotsFile.Close()
|
||||
defer func() {
|
||||
if err := robotsFile.Close(); err != nil {
|
||||
t.Fatalf("can't close output file: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Parse robots.txt
|
||||
rules, err := parseRobotsTxt(robotsFile)
|
||||
@@ -158,8 +162,8 @@ func TestDataFileConversion(t *testing.T) {
|
||||
}
|
||||
|
||||
if strings.ToLower(*outputFormat) == "yaml" {
|
||||
var actualData []interface{}
|
||||
var expectedData []interface{}
|
||||
var actualData []any
|
||||
var expectedData []any
|
||||
|
||||
err = yaml.Unmarshal(actualOutput, &actualData)
|
||||
if err != nil {
|
||||
@@ -178,8 +182,8 @@ func TestDataFileConversion(t *testing.T) {
|
||||
t.Errorf("Output mismatch for %s\nExpected:\n%s\n\nActual:\n%s", tc.name, expectedStr, actualStr)
|
||||
}
|
||||
} else {
|
||||
var actualData []interface{}
|
||||
var expectedData []interface{}
|
||||
var actualData []any
|
||||
var expectedData []any
|
||||
|
||||
err = json.Unmarshal(actualOutput, &actualData)
|
||||
if err != nil {
|
||||
@@ -419,6 +423,6 @@ Disallow: /`
|
||||
|
||||
// compareData performs a deep comparison of two data structures,
|
||||
// ignoring differences that are semantically equivalent in YAML/JSON
|
||||
func compareData(actual, expected interface{}) bool {
|
||||
func compareData(actual, expected any) bool {
|
||||
return reflect.DeepEqual(actual, expected)
|
||||
}
|
||||
Reference in new issue
Block a user