anubis.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. package lib
  2. import (
  3. "context"
  4. "crypto/ed25519"
  5. "crypto/rand"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "log/slog"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "strings"
  14. "time"
  15. "github.com/golang-jwt/jwt/v5"
  16. "github.com/google/cel-go/common/types"
  17. "github.com/google/uuid"
  18. "github.com/prometheus/client_golang/prometheus"
  19. "github.com/prometheus/client_golang/prometheus/promauto"
  20. "github.com/TecharoHQ/anubis"
  21. "github.com/TecharoHQ/anubis/decaymap"
  22. "github.com/TecharoHQ/anubis/internal"
  23. "github.com/TecharoHQ/anubis/internal/dnsbl"
  24. "github.com/TecharoHQ/anubis/internal/ogtags"
  25. "github.com/TecharoHQ/anubis/lib/challenge"
  26. "github.com/TecharoHQ/anubis/lib/config"
  27. "github.com/TecharoHQ/anubis/lib/localization"
  28. "github.com/TecharoHQ/anubis/lib/policy"
  29. "github.com/TecharoHQ/anubis/lib/policy/checker"
  30. "github.com/TecharoHQ/anubis/lib/store"
  31. // challenge implementations
  32. _ "github.com/TecharoHQ/anubis/lib/challenge/metarefresh"
  33. _ "github.com/TecharoHQ/anubis/lib/challenge/preact"
  34. _ "github.com/TecharoHQ/anubis/lib/challenge/proofofwork"
  35. )
  36. var (
  37. challengesIssued = promauto.NewCounterVec(prometheus.CounterOpts{
  38. Name: "anubis_challenges_issued",
  39. Help: "The total number of challenges issued",
  40. }, []string{"method"})
  41. challengesValidated = promauto.NewCounterVec(prometheus.CounterOpts{
  42. Name: "anubis_challenges_validated",
  43. Help: "The total number of challenges validated",
  44. }, []string{"method"})
  45. droneBLHits = promauto.NewCounterVec(prometheus.CounterOpts{
  46. Name: "anubis_dronebl_hits",
  47. Help: "The total number of hits from DroneBL",
  48. }, []string{"status"})
  49. failedValidations = promauto.NewCounterVec(prometheus.CounterOpts{
  50. Name: "anubis_failed_validations",
  51. Help: "The total number of failed validations",
  52. }, []string{"method"})
  53. requestsProxied = promauto.NewCounterVec(prometheus.CounterOpts{
  54. Name: "anubis_proxied_requests_total",
  55. Help: "Number of requests proxied through Anubis to upstream targets",
  56. }, []string{"host"})
  57. )
  58. type Server struct {
  59. next http.Handler
  60. store store.Interface
  61. mux *http.ServeMux
  62. policy *policy.ParsedConfig
  63. OGTags *ogtags.OGTagCache
  64. logger *slog.Logger
  65. opts Options
  66. ed25519Priv ed25519.PrivateKey
  67. hs512Secret []byte
  68. }
  69. func (s *Server) getTokenKeyfunc() jwt.Keyfunc {
  70. // return ED25519 key if HS512 is not set
  71. if len(s.hs512Secret) == 0 {
  72. return func(token *jwt.Token) (interface{}, error) {
  73. return s.ed25519Priv.Public().(ed25519.PublicKey), nil
  74. }
  75. } else {
  76. return func(token *jwt.Token) (interface{}, error) {
  77. return s.hs512Secret, nil
  78. }
  79. }
  80. }
  81. func (s *Server) getChallenge(r *http.Request) (*challenge.Challenge, error) {
  82. id := r.FormValue("id")
  83. j := store.JSON[challenge.Challenge]{Underlying: s.store}
  84. chall, err := j.Get(r.Context(), "challenge:"+id)
  85. return &chall, err
  86. }
  87. func (s *Server) issueChallenge(ctx context.Context, r *http.Request, lg *slog.Logger, cr policy.CheckResult, rule *policy.Bot) (*challenge.Challenge, error) {
  88. if cr.Rule != config.RuleChallenge {
  89. slog.Error("this should be impossible, asked to issue a challenge but the rule is not a challenge rule", "cr", cr, "rule", rule)
  90. //return nil, errors.New("[unexpected] this codepath should be impossible, asked to issue a challenge for a non-challenge rule")
  91. }
  92. id, err := uuid.NewV7()
  93. if err != nil {
  94. return nil, err
  95. }
  96. var randomData = make([]byte, 64)
  97. if _, err := rand.Read(randomData); err != nil {
  98. return nil, err
  99. }
  100. chall := challenge.Challenge{
  101. ID: id.String(),
  102. Method: rule.Challenge.Algorithm,
  103. RandomData: fmt.Sprintf("%x", randomData),
  104. IssuedAt: time.Now(),
  105. Difficulty: rule.Challenge.Difficulty,
  106. PolicyRuleHash: rule.Hash(),
  107. Metadata: map[string]string{
  108. "User-Agent": r.Header.Get("User-Agent"),
  109. "X-Real-Ip": r.Header.Get("X-Real-Ip"),
  110. },
  111. }
  112. j := store.JSON[challenge.Challenge]{Underlying: s.store}
  113. if err := j.Set(ctx, "challenge:"+id.String(), chall, 30*time.Minute); err != nil {
  114. return nil, err
  115. }
  116. lg.Info("new challenge issued", "challenge", id.String())
  117. return &chall, err
  118. }
  119. func (s *Server) hydrateChallengeRule(rule *policy.Bot, chall *challenge.Challenge, lg *slog.Logger) *policy.Bot {
  120. if chall == nil {
  121. return rule
  122. }
  123. if rule == nil {
  124. rule = &policy.Bot{
  125. Rules: &checker.List{},
  126. }
  127. }
  128. if chall.Difficulty == 0 {
  129. // fall back to whatever the policy currently says or the global default
  130. if rule.Challenge != nil && rule.Challenge.Difficulty != 0 {
  131. chall.Difficulty = rule.Challenge.Difficulty
  132. } else {
  133. chall.Difficulty = s.policy.DefaultDifficulty
  134. }
  135. }
  136. if rule.Challenge == nil {
  137. lg.Warn("rule missing challenge configuration; using stored challenge metadata", "rule", rule.Name)
  138. rule.Challenge = &config.ChallengeRules{}
  139. }
  140. if rule.Challenge.Difficulty == 0 {
  141. rule.Challenge.Difficulty = chall.Difficulty
  142. }
  143. if rule.Challenge.ReportAs != 0 {
  144. s.logger.Warn("[DEPRECATION] the report_as field in this bot rule is deprecated, see https://github.com/TecharoHQ/anubis/issues/1310 for more information", "bot_name", rule.Name, "difficulty", rule.Challenge.Difficulty, "report_as", rule.Challenge.ReportAs)
  145. }
  146. if rule.Challenge.Algorithm == "" {
  147. rule.Challenge.Algorithm = chall.Method
  148. }
  149. return rule
  150. }
  151. func (s *Server) maybeReverseProxyHttpStatusOnly(w http.ResponseWriter, r *http.Request) {
  152. s.maybeReverseProxy(w, r, true)
  153. }
  154. func (s *Server) maybeReverseProxyOrPage(w http.ResponseWriter, r *http.Request) {
  155. s.maybeReverseProxy(w, r, false)
  156. }
  157. func (s *Server) maybeReverseProxy(w http.ResponseWriter, r *http.Request, httpStatusOnly bool) {
  158. lg := internal.GetRequestLogger(s.logger, r)
  159. if val, _ := s.store.Get(r.Context(), fmt.Sprintf("ogtags:allow:%s%s", r.Host, r.URL.String())); val != nil {
  160. lg.Debug("serving opengraph tag asset")
  161. s.ServeHTTPNext(w, r)
  162. return
  163. }
  164. // Adjust cookie path if base prefix is not empty
  165. cookiePath := "/"
  166. if anubis.BasePrefix != "" {
  167. cookiePath = strings.TrimSuffix(anubis.BasePrefix, "/") + "/"
  168. }
  169. cr, rule, err := s.check(r, lg)
  170. if err != nil {
  171. lg.Error("check failed", "err", err)
  172. localizer := localization.GetLocalizer(r)
  173. s.respondWithError(w, r, fmt.Sprintf("%s \"maybeReverseProxy\"", localizer.T("internal_server_error")), makeCode(err))
  174. return
  175. }
  176. r.Header.Add("X-Anubis-Rule", cr.Name)
  177. r.Header.Add("X-Anubis-Action", string(cr.Rule))
  178. lg = lg.With("check_result", cr)
  179. policy.Applications.WithLabelValues(cr.Name, string(cr.Rule)).Add(1)
  180. ip := r.Header.Get("X-Real-Ip")
  181. if s.handleDNSBL(w, r, ip, lg) {
  182. return
  183. }
  184. if s.checkRules(w, r, cr, lg, rule) {
  185. return
  186. }
  187. ckie, err := r.Cookie(anubis.CookieName)
  188. if err != nil {
  189. lg.Debug("cookie not found", "path", r.URL.Path)
  190. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  191. s.RenderIndex(w, r, cr, rule, httpStatusOnly)
  192. return
  193. }
  194. if err := ckie.Valid(); err != nil {
  195. lg.Debug("cookie is invalid", "err", err)
  196. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  197. s.RenderIndex(w, r, cr, rule, httpStatusOnly)
  198. return
  199. }
  200. if time.Now().After(ckie.Expires) && !ckie.Expires.IsZero() {
  201. lg.Debug("cookie expired", "path", r.URL.Path)
  202. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  203. s.RenderIndex(w, r, cr, rule, httpStatusOnly)
  204. return
  205. }
  206. token, err := jwt.ParseWithClaims(ckie.Value, jwt.MapClaims{}, s.getTokenKeyfunc(), jwt.WithExpirationRequired(), jwt.WithStrictDecoding())
  207. if err != nil || !token.Valid {
  208. lg.Debug("invalid token", "path", r.URL.Path, "err", err)
  209. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  210. s.RenderIndex(w, r, cr, rule, httpStatusOnly)
  211. return
  212. }
  213. claims, ok := token.Claims.(jwt.MapClaims)
  214. if !ok {
  215. lg.Debug("invalid token claims type", "path", r.URL.Path)
  216. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  217. s.RenderIndex(w, r, cr, rule, httpStatusOnly)
  218. return
  219. }
  220. policyRule, ok := claims["policyRule"].(string)
  221. if !ok {
  222. lg.Debug("policyRule claim is not a string")
  223. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  224. s.RenderIndex(w, r, cr, rule, httpStatusOnly)
  225. return
  226. }
  227. if policyRule != rule.Hash() {
  228. lg.Debug("user originally passed with a different rule, issuing new challenge", "old", policyRule, "new", rule.Name)
  229. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  230. s.RenderIndex(w, r, cr, rule, httpStatusOnly)
  231. return
  232. }
  233. if s.opts.JWTRestrictionHeader != "" && claims["restriction"] != internal.SHA256sum(r.Header.Get(s.opts.JWTRestrictionHeader)) {
  234. lg.Debug("JWT restriction header is invalid")
  235. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  236. s.RenderIndex(w, r, cr, rule, httpStatusOnly)
  237. return
  238. }
  239. r.Header.Add("X-Anubis-Status", "PASS")
  240. s.ServeHTTPNext(w, r)
  241. }
  242. func (s *Server) checkRules(w http.ResponseWriter, r *http.Request, cr policy.CheckResult, lg *slog.Logger, rule *policy.Bot) bool {
  243. // Adjust cookie path if base prefix is not empty
  244. cookiePath := "/"
  245. if anubis.BasePrefix != "" {
  246. cookiePath = strings.TrimSuffix(anubis.BasePrefix, "/") + "/"
  247. }
  248. localizer := localization.GetLocalizer(r)
  249. switch cr.Rule {
  250. case config.RuleAllow:
  251. lg.Debug("allowing traffic to origin (explicit)")
  252. s.ServeHTTPNext(w, r)
  253. return true
  254. case config.RuleDeny:
  255. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  256. lg.Info("explicit deny")
  257. if rule == nil {
  258. lg.Error("rule is nil, cannot calculate checksum")
  259. s.respondWithError(w, r, fmt.Sprintf("%s \"maybeReverseProxy.RuleDeny\"", localizer.T("internal_server_error")), makeCode(ErrActualAnubisBug))
  260. return true
  261. }
  262. hash := rule.Hash()
  263. lg.Debug("rule hash", "hash", hash)
  264. s.respondWithStatus(w, r, fmt.Sprintf("%s %s", localizer.T("access_denied"), hash), "", s.policy.StatusCodes.Deny)
  265. return true
  266. case config.RuleChallenge:
  267. lg.Debug("challenge requested")
  268. case config.RuleBenchmark:
  269. lg.Debug("serving benchmark page")
  270. s.RenderBench(w, r)
  271. return true
  272. default:
  273. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  274. lg.Error("CONFIG ERROR: unknown rule", "rule", cr.Rule)
  275. s.respondWithError(w, r, fmt.Sprintf("%s \"maybeReverseProxy.Rules\"", localizer.T("internal_server_error")), makeCode(ErrActualAnubisBug))
  276. return true
  277. }
  278. return false
  279. }
  280. func (s *Server) handleDNSBL(w http.ResponseWriter, r *http.Request, ip string, lg *slog.Logger) bool {
  281. db := &store.JSON[dnsbl.DroneBLResponse]{Underlying: s.store, Prefix: "dronebl:"}
  282. if s.policy.DNSBL && ip != "" {
  283. resp, err := db.Get(r.Context(), ip)
  284. if err != nil {
  285. lg.Debug("looking up ip in dnsbl")
  286. resp, err := dnsbl.Lookup(ip)
  287. if err != nil {
  288. lg.Error("can't look up ip in dnsbl", "err", err)
  289. }
  290. db.Set(r.Context(), ip, resp, 24*time.Hour)
  291. droneBLHits.WithLabelValues(resp.String()).Inc()
  292. }
  293. if resp != dnsbl.AllGood {
  294. lg.Info("DNSBL hit", "status", resp.String())
  295. localizer := localization.GetLocalizer(r)
  296. s.respondWithStatus(w, r, fmt.Sprintf("%s: %s, %s https://dronebl.org/lookup?ip=%s",
  297. localizer.T("dronebl_entry"),
  298. resp.String(),
  299. localizer.T("see_dronebl_lookup"),
  300. ip), "", s.policy.StatusCodes.Deny)
  301. return true
  302. }
  303. }
  304. return false
  305. }
  306. func (s *Server) MakeChallenge(w http.ResponseWriter, r *http.Request) {
  307. lg := internal.GetRequestLogger(s.logger, r)
  308. localizer := localization.GetLocalizer(r)
  309. redir := r.FormValue("redir")
  310. if redir == "" {
  311. w.WriteHeader(http.StatusBadRequest)
  312. encoder := json.NewEncoder(w)
  313. lg.Error("invalid invocation of MakeChallenge", "redir", redir)
  314. encoder.Encode(struct {
  315. Error string `json:"error"`
  316. }{
  317. Error: localizer.T("invalid_invocation"),
  318. })
  319. return
  320. }
  321. r.URL.Path = redir
  322. encoder := json.NewEncoder(w)
  323. cr, rule, err := s.check(r, lg)
  324. if err != nil {
  325. lg.Error("check failed", "err", err)
  326. w.WriteHeader(http.StatusInternalServerError)
  327. err := encoder.Encode(struct {
  328. Error string `json:"error"`
  329. }{
  330. Error: fmt.Sprintf("%s \"makeChallenge\"", localizer.T("internal_server_error")),
  331. })
  332. if err != nil {
  333. lg.Error("failed to encode error response", "err", err)
  334. w.WriteHeader(http.StatusInternalServerError)
  335. }
  336. return
  337. }
  338. lg = lg.With("check_result", cr)
  339. chall, err := s.issueChallenge(r.Context(), r, lg, cr, rule)
  340. if err != nil {
  341. lg.Error("failed to fetch or issue challenge", "err", err)
  342. w.WriteHeader(http.StatusInternalServerError)
  343. err := encoder.Encode(struct {
  344. Error string `json:"error"`
  345. }{
  346. Error: fmt.Sprintf("%s \"makeChallenge\"", localizer.T("internal_server_error")),
  347. })
  348. if err != nil {
  349. lg.Error("failed to encode error response", "err", err)
  350. w.WriteHeader(http.StatusInternalServerError)
  351. }
  352. return
  353. }
  354. s.SetCookie(w, CookieOpts{Host: r.Host, Name: anubis.TestCookieName, Value: chall.ID})
  355. err = encoder.Encode(struct {
  356. Rules *config.ChallengeRules `json:"rules"`
  357. Challenge string `json:"challenge"`
  358. ID string `json:"id"`
  359. }{
  360. Rules: rule.Challenge,
  361. Challenge: chall.RandomData,
  362. ID: chall.ID,
  363. })
  364. if err != nil {
  365. lg.Error("failed to encode challenge", "err", err)
  366. w.WriteHeader(http.StatusInternalServerError)
  367. return
  368. }
  369. lg.Debug("made challenge", "challenge", chall, "rules", rule.Challenge, "cr", cr)
  370. challengesIssued.WithLabelValues("api").Inc()
  371. }
  372. func (s *Server) PassChallenge(w http.ResponseWriter, r *http.Request) {
  373. lg := internal.GetRequestLogger(s.logger, r)
  374. localizer := localization.GetLocalizer(r)
  375. redir := r.FormValue("redir")
  376. redirURL, err := url.ParseRequestURI(redir)
  377. if err != nil {
  378. lg.Error("invalid redirect", "err", err)
  379. s.respondWithStatus(w, r, localizer.T("invalid_redirect"), makeCode(err), http.StatusBadRequest)
  380. return
  381. }
  382. switch redirURL.Scheme {
  383. case "", "http", "https":
  384. // allowed
  385. default:
  386. lg.Error("XSS attempt blocked, invalid redirect scheme", "scheme", redirURL.Scheme)
  387. s.respondWithStatus(w, r, localizer.T("invalid_redirect"), "", http.StatusBadRequest)
  388. return
  389. }
  390. // Adjust cookie path if base prefix is not empty
  391. cookiePath := "/"
  392. if anubis.BasePrefix != "" {
  393. cookiePath = strings.TrimSuffix(anubis.BasePrefix, "/") + "/"
  394. }
  395. if _, err := r.Cookie(anubis.TestCookieName); errors.Is(err, http.ErrNoCookie) {
  396. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  397. s.ClearCookie(w, CookieOpts{Name: anubis.TestCookieName, Host: r.Host})
  398. lg.Warn("user has cookies disabled, this is not an anubis bug")
  399. s.respondWithError(w, r, localizer.T("cookies_disabled"), "")
  400. return
  401. }
  402. // used by the path checker rule
  403. r.URL = redirURL
  404. urlParsed, err := r.URL.Parse(redir)
  405. if err != nil {
  406. s.respondWithError(w, r, localizer.T("redirect_not_parseable"), makeCode(err))
  407. return
  408. }
  409. if (len(urlParsed.Host) > 0 && len(s.opts.RedirectDomains) != 0 && !matchRedirectDomain(s.opts.RedirectDomains, urlParsed.Host)) || urlParsed.Host != r.URL.Host {
  410. lg.Debug("domain not allowed", "domain", urlParsed.Host)
  411. s.respondWithError(w, r, localizer.T("redirect_domain_not_allowed"), "")
  412. return
  413. }
  414. cr, rule, err := s.check(r, lg)
  415. if err != nil {
  416. lg.Error("check failed", "err", err)
  417. s.respondWithError(w, r, fmt.Sprintf("%s \"passChallenge\"", localizer.T("internal_server_error")), makeCode(err))
  418. return
  419. }
  420. lg = lg.With("check_result", cr)
  421. chall, err := s.getChallenge(r)
  422. if err != nil {
  423. lg.Error("getChallenge failed", "err", err)
  424. s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), rule.Challenge.Algorithm), makeCode(err))
  425. return
  426. }
  427. if chall.Spent {
  428. lg.Error("double spend prevented", "reason", "double_spend")
  429. s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), "double_spend"), "")
  430. return
  431. }
  432. rule = s.hydrateChallengeRule(rule, chall, lg)
  433. impl, ok := challenge.Get(chall.Method)
  434. if !ok {
  435. lg.Error("check failed", "err", err)
  436. s.respondWithError(w, r, fmt.Sprintf("%s: %s", localizer.T("internal_server_error"), rule.Challenge.Algorithm), makeCode(ErrActualAnubisBug))
  437. return
  438. }
  439. lg = lg.With("challenge", chall.ID)
  440. in := &challenge.ValidateInput{
  441. Challenge: chall,
  442. Rule: rule,
  443. Store: s.store,
  444. }
  445. if err := impl.Validate(r, lg, in); err != nil {
  446. failedValidations.WithLabelValues(rule.Challenge.Algorithm).Inc()
  447. var cerr *challenge.Error
  448. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  449. lg.Debug("challenge validate call failed", "err", err)
  450. switch {
  451. case errors.As(err, &cerr):
  452. switch {
  453. case errors.Is(err, challenge.ErrFailed):
  454. lg.Error("challenge failed", "err", err)
  455. s.respondWithStatus(w, r, cerr.PublicReason, makeCode(err), cerr.StatusCode)
  456. return
  457. case errors.Is(err, challenge.ErrInvalidFormat), errors.Is(err, challenge.ErrMissingField):
  458. lg.Error("invalid challenge format", "err", err)
  459. s.respondWithError(w, r, cerr.PublicReason, makeCode(err))
  460. return
  461. }
  462. }
  463. }
  464. // generate JWT cookie
  465. var tokenString string
  466. // check if JWTRestrictionHeader is set and header is in request
  467. claims := jwt.MapClaims{
  468. "challenge": chall.ID,
  469. "method": rule.Challenge.Algorithm,
  470. "policyRule": rule.Hash(),
  471. "action": string(cr.Rule),
  472. }
  473. if s.opts.JWTRestrictionHeader != "" {
  474. if r.Header.Get(s.opts.JWTRestrictionHeader) == "" {
  475. lg.Error("JWTRestrictionHeader is set in config but not found in request, please check your reverse proxy config.")
  476. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  477. s.respondWithError(w, r, "failed to sign JWT", makeCode(err))
  478. return
  479. } else {
  480. claims["restriction"] = internal.SHA256sum(r.Header.Get(s.opts.JWTRestrictionHeader))
  481. }
  482. }
  483. if s.opts.DifficultyInJWT {
  484. claims["difficulty"] = rule.Challenge.Difficulty
  485. }
  486. tokenString, err = s.signJWT(claims)
  487. if err != nil {
  488. lg.Error("failed to sign JWT", "err", err)
  489. s.ClearCookie(w, CookieOpts{Path: cookiePath, Host: r.Host})
  490. s.respondWithError(w, r, localizer.T("failed_to_sign_jwt"), makeCode(err))
  491. return
  492. }
  493. s.SetCookie(w, CookieOpts{Path: cookiePath, Host: r.Host, Value: tokenString})
  494. chall.Spent = true
  495. j := store.JSON[challenge.Challenge]{Underlying: s.store}
  496. if err := j.Set(r.Context(), "challenge:"+chall.ID, *chall, 30*time.Minute); err != nil {
  497. lg.Debug("can't update information about challenge", "err", err)
  498. }
  499. challengesValidated.WithLabelValues(rule.Challenge.Algorithm).Inc()
  500. lg.Debug("challenge passed, redirecting to app")
  501. http.Redirect(w, r, redir, http.StatusFound)
  502. }
  503. func cr(name string, rule config.Rule, weight int) policy.CheckResult {
  504. return policy.CheckResult{
  505. Name: name,
  506. Rule: rule,
  507. Weight: weight,
  508. }
  509. }
  510. // Check evaluates the list of rules, and returns the result
  511. func (s *Server) check(r *http.Request, lg *slog.Logger) (policy.CheckResult, *policy.Bot, error) {
  512. host := r.Header.Get("X-Real-Ip")
  513. if host == "" {
  514. return decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf("[misconfiguration] X-Real-Ip header is not set")
  515. }
  516. addr := net.ParseIP(host)
  517. if addr == nil {
  518. return decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf("[misconfiguration] %q is not an IP address", host)
  519. }
  520. weight := 0
  521. for _, b := range s.policy.Bots {
  522. match, err := b.Rules.Check(r)
  523. if err != nil {
  524. return decaymap.Zilch[policy.CheckResult](), nil, fmt.Errorf("can't run check %s: %w", b.Name, err)
  525. }
  526. if match {
  527. switch b.Action {
  528. case config.RuleDeny, config.RuleAllow, config.RuleBenchmark, config.RuleChallenge:
  529. return cr("bot/"+b.Name, b.Action, weight), &b, nil
  530. case config.RuleWeigh:
  531. lg.Debug("adjusting weight", "name", b.Name, "delta", b.Weight.Adjust)
  532. policy.Applications.WithLabelValues("bot/"+b.Name, "WEIGH").Add(1)
  533. weight += b.Weight.Adjust
  534. }
  535. }
  536. }
  537. for _, t := range s.policy.Thresholds {
  538. result, _, err := t.Program.ContextEval(r.Context(), &policy.ThresholdRequest{Weight: weight})
  539. if err != nil {
  540. lg.Error("error when evaluating threshold expression", "expression", t.Expression.String(), "err", err)
  541. continue
  542. }
  543. var matches bool
  544. if val, ok := result.(types.Bool); ok {
  545. matches = bool(val)
  546. }
  547. if matches {
  548. return cr("threshold/"+t.Name, t.Action, weight), &policy.Bot{
  549. Challenge: t.Challenge,
  550. Rules: &checker.List{},
  551. }, nil
  552. }
  553. }
  554. return cr("default/allow", config.RuleAllow, weight), &policy.Bot{
  555. Challenge: &config.ChallengeRules{
  556. Difficulty: s.policy.DefaultDifficulty,
  557. Algorithm: config.DefaultAlgorithm,
  558. },
  559. Rules: &checker.List{},
  560. }, nil
  561. }